Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 652
Mathias Vielwerth Avatar asked Feb 25 '23 03:02

Mathias Vielwerth


1 Answers

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();
}
like image 118
Mathias Vielwerth Avatar answered Mar 04 '23 13:03

Mathias Vielwerth