System.setProperty and System.getProperty

If you see source code of System Class it has following class variable

private static Properties props;

As for properties class you can think of it as a HashMap. It actually extends HashMap.

public class Properties extends Hashtable<Object,Object>

When you call

setProperty(String key, String value)

it actually does

props.setProperty(key, value);

This is just the summary(Security manager checks are also involved).

Now why did I say it is per JVM instance?

When you start a Java process a separate JVM instance is created that runs your process. Also since props is a Class variable(not an instance variable) just one copy of it will be present in the corresponding Class instance which will be set when that class is loaded. Now this is under the assumption that you do not have any of your custom class loaders in which case behavior might be different. But for simplistic scenario you System.setProperty() and System.getProperty() will set system properties that you can access via any class running as a part of that java process(JVM).


System class has a static member variable named props which is of type Properties. Adding to that, Properties is a subtype of Hashtable class. All the property values are stored as Key and Value. So, datastore is Hashtable.Answering the other question, You can very well use System.getProperty(propertyKey) method throughout your application since it is a public static method. You haven't understood how java programs work. When you run a Java program, you are actually starting a JVM instance. That instance will have its own System properties. That is where you have to put your property. When you run the other program, that will have its own System properties. So, you cannot expect a property which you set in one JVM instance to be accessible from another JVM instance! You can access the System.getProperty(propertyKey) in all classes running in the same JVM instance. Hope you can understand!

Tags:

Java