Java - is setProperty safe [duplicate]
Solution 1:
It depends what you mean by safe.
It is good practice1 treat the System Properties object as read only, but you can't rely on 3rd-party libraries to do that.
If you are worried about "trusted" 3rd-party code seeing or changing your application's properties, don't use System Properties to represent them. Create your own Properties object and put your properties there. This is probably the simplest approach overall.
If you use sandboxing, you can prevent untrusted code from access the System Properties ... provided that your code doesn't leak the System Properties object to the untrusted code. (The access checks are implemented in the
System
methods ...)A Properties object is thread-safe ... if you are referring to that kind of safety.
1 - Occasionally it is necessary to modify system properties programmatically. However, you can end up with fragile applications by doing this. The system properties are typically used to configure JVM services during the initialization. If the order of class initialization changes for some reason, you could find that your application code is now setting the properties too late. If possible, it is better to set the properties via -D
command line parameters.
Solution 2:
If you need to worry about the behavior of libraries, you need to learn about and use a security policy and a SecurityManager. Amongst other things, this will allow you to restrict the use of System.setProperty
.