Is *this* really the best way to start a second JVM from Java code?

Robert Petermeier picture Robert Petermeier · Aug 4, 2009 · Viewed 22.6k times · Source

This is a followup to my own previous question and I'm kind of embarassed to ask this... But anyway: how would you start a second JVM from a standalone Java program in a system-independent way? And without relying on for instance an env variable like JAVA_HOME as that might point to a different JRE than the one that is currently running. I came up with the following code which actually works but feels just a little awkward:

public static void startSecondJVM() throws Exception {
    String separator = System.getProperty("file.separator");
    String classpath = System.getProperty("java.class.path");
    String path = System.getProperty("java.home")
                + separator + "bin" + separator + "java";
    ProcessBuilder processBuilder = 
                new ProcessBuilder(path, "-cp", 
                classpath, 
                AnotherClassWithMainMethod.class.getName());
    Process process = processBuilder.start();
    process.waitFor();
}

Also, the currently running JVM might have been started with some other parameters (-D, -X..., ...) that the second JVM would not know about.

Answer

Stephen C picture Stephen C · Aug 5, 2009

I think that the answer is "Yes". This probably as good as you can do in Java using system independent code. But be aware that even this is only relatively system independent. For example, in some systems:

  1. the JAVA_HOME variable may not have been set,
  2. the command name used to launch a JVM might be different (e.g. if it is not a Sun JVM), or
  3. the command line options might be different (e.g. if it is not a Sun JVM).

If I was aiming for maximum portability in launching a (second) JVM, I think I would do it using wrapper scripts.