Is it possible to set an environment variable at runtime from Java?

If my intuition is correct, and you actually want to modify the environment for the benefit of a spawned (forked) sub-process (Runtime.getRuntime().exec()), then use ProcessBuilder instead of exec(). You can build a custom environment via your ProcessBuilder instance’s environment() method.

If this is not what you are trying to achieve then kindly disregard this answer.


UPDATE

The answer to your three updated, specific questions is as follows:

  1. Can we modify the environment of the current process?
    • Not easily. Depends whether you want to change the process’ environment, to change the value(s) returned by System.getenv() in the same JVM, or both.
    • As Greg Hewgill pointed out, to change the current process’ environment you can call setenv or its platform-specific equivalent via JNI. You may also employ the extremely convoluted method from point 2 below, which works for any process (provided you have the permissions.) However, be aware that in most JVMs this change might never be reflected in the values returned by System.getenv(), as the environment is more often than not cached at virtual machine startup in a java.util.Map (or equivalent.)
    • To change the JVM’s cached copy of the environment, when a cache is used (see the source code in System.java in whichever JVM distribution you will be using to deploy), you may try hacking the implementation (via class loading order, reflection, or instrumentation.) In the case of SUN’s v1.6 JVM, for example, the environment cache is managed by the undocumented ProcessEnvironment class (which you can patch.)
  2. Can we modify the environment of the parent process?
  3. Can we modify the environment of the child process?
    • Yes, through ProcessBuilder when spawning the process.
    • If the process has already been spawned when the environment alteration is required, you need method 2 above (or some equally convoluted method, such as code-injection at spawn time, ulteriorly controlled through e.g. socket by the parent process.)

Note that all methods above, except for the one involving ProcessBuilder, are brittle, error prone, non-portable to various degrees, and prone to race conditions in multi-threaded environments.

Leave a Comment