javajvmheap-memoryrebootrelaunch

Re launch JVM with bigger heap space


I want to be able to execute the .Jar file, and if the heap space isn't set big enough, it should launch a new JVM with the same .Jar file, but set with a bigger heap space, and then close the first JVM and .Jar.

I've tried using the ProcessBuilder, but I can't get it to work.

It has to work cross platform.

-ONi


Solution

  • I have found the solution, and it works cross platform. To restart the JVM from code, use the following. This answer is taken from another question I found after hours of search in here. If you want, you can follow it with an System.exit(0), to terminate the JVM that started the new process, after a call to this method.

    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, "-Xmx1024m", "-cp",
                classpath, 
                Main.class.getName());
        Process process = processBuilder.start();
    }