When to use environment variables vs. system properties?

James Raitsev picture James Raitsev · Dec 25, 2012 · Viewed 8.7k times · Source

I wonder which of the following is a preferred approach?

We can set things up as APP_HOME=/path/to/file (export in .profile or something along those lines) and access it as System.getenv("APP_HOME")

Or, alternatively using properties as -DAPP_HOME=/path/to/file and access it as System.getProperty("APP_HOME")

Now .. either one will make the value available for the application stand point, but is either approach preferred? Why? When?

Answer

ruakh picture ruakh · Dec 25, 2012

The Javadoc for System.getenv(String) addresses this question directly, saying:

System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH).

(emphasis mine).