views:

17882

answers:

4

How do I set environment variables from Java? I see that I can do this for subprocesses using ProcessBuilder. I have several subprocesses to start, though, so I'd rather modify the current process's environment and let the subprocesses inherit it.

There's a System.getenv(String) for getting a single environment variable. I can also get a Map of the complete set of environment variables with System.getenv(). But calling put() on that Map throws an UnsupportedOperationException -- apparently they mean for the environment to be read only. And there's no System.setenv().

So, is there any way to set environment variables in the currently running process? If so, how? If not, what's the rationale? (Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?) And if not, any good suggestions for managing the environment variable changes that I'm going to need to be feeding to several subprocesses?

A: 

You can pass parameters into your initial java process with -D:

java -cp <classpath> -Dkey1=value -Dkey2=value ...
matt b
The values are not known at execution time; they become known during the program's execution when the user provides/selects them. And that sets only system properties, not environment variables.
skiphoppy
Then in that case you probably want to find a regular way (via the args[] parameter to the main method) to invoke your subprocesses.
matt b
matt b, the regular way is via ProcessBuilder, as mentioned in my original question. :)
skiphoppy
-D parameters are available through `System.getProperty` and are not the same as `System.getenv`.Besides, the `System` class also allows to set these properties statically using `setProperty`
anirvan
+10  A: 

(Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?)

I think you've hit the nail on the head.

A possible way to ease the burden would be to factor out a method

void setUpEnvironment(ProcessBuilder builder) {
    Map<String, String> env = builder.environment();
    // blah blah
}

and pass any ProcessBuilders through it before starting them.

Also, you probably already know this, but you can start more than one process with the same ProcessBuilder. So if your subprocesses are the same, you don't need to do this setup over and over.

Michael Myers
It's a shame management won't let me use a different portable language for running this set of evil, obsolete subprocesses, then. :)
skiphoppy
@skiphoppy: no tool can set the parent's environment -- it's not a tool issue, it's an OS issue.
S.Lott
S.Lott, I'm not looking to set a parent's environment. I'm looking to set my own environment.
skiphoppy
Thanks, mmyers. I think I'm definitely going to have to factor out such a method. I already have a ProcessUtils class, so it's going to have to grow to manage changes to the environment.
skiphoppy
+1  A: 

Poking around online, it looks like it might be possible to do this with JNI. You'd then have to make a call to putenv() from C, and you'd (presumably) have to do it in a way that worked on both Windows and UNIX.

If all that can be done, it surely wouldn't be too hard for Java itself to support this instead of putting me in a straight jacket.

A Perl-speaking friend elsewhere suggests that this is because environment variables are process global and Java is striving for good isolation for good design.

skiphoppy
Yes, you can set the processes environment from C code. But I wouldn't count on that working in Java. There is a good chance that the JVM copies the environment into Java String objects during startup, so your changes would not be used for future JVM operations.
Darron
Thanks for the warning, Darron. There's probably a good chance you're right.
skiphoppy
+2  A: 
public static void set(Map<String, String> newenv) throws Exception {
    Class[] classes = Collections.class.getDeclaredClasses();
    Map<String, String> env = System.getenv();
    for(Class cl : classes) {
        if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
            Field field = cl.getDeclaredField("m");
            field.setAccessible(true);
            Object obj = field.get(env);
            Map<String, String> map = (Map<String, String>) obj;
            map.clear();
            map.putAll(newenv);
        }
    }
}
Dude ... does it really work???
skiphoppy
It sounds like that would modify the map in memory, but would it save the value to the system?
Jon
well it does change the memory map of environment variables. i guess that suffices in a whole lot of use-cases. @Edward - gosh, it's hard to imagine how this solution was figured out in the first place!
anirvan