Skip to content
Advertisement

Spawn another process on same JVM

From a Java application I want to run another Java application on the same Java installation but in a separate process.

AFAIK for a new process I would use ProcessBuilder to run a command like

java -jar my.jar

but what if java is in a different directory, or should be java.exe since we are on Windows, or java.exe has some other name since the first application was jlinked and jpackaged?

Edit: What I learned meanwhile is that a jpackaged application comes with a native executable that sits in front of the JVM but passes all arguments to the application. That means it is no longer possible to specify an alternative jar to be executed, and some other mechanism is necessary.

Advertisement

Answer

If jlink image used within jpackage based apps is built without using the --strip-native-commands flag then the runtime image will contain bin/java (or bin/java.exe and bin/javaw.exe on Windows).

This will mean that you should be able to determine a path to launch a new JVM which works inside or outside of jpackage apps just based on the current runtime’s java.home and by appending extra VM arguments in normal way for the classpath and main / module of the other application.

On Windows the environment property echo %PATHEXT% usually contains .EXE so the following should specify the java executable for the current runtime without needing to add the correct file extension on Windows:

String java = Path.of(System.getProperty("java.home"),"bin", "java").toString();

You can test above inside your jpackage and non-jpackaged app with a simple one-liner (note that this is not proper way to use ProcessBuilder):

new ProcessBuilder(java, "-version").start().getErrorStream().transferTo(System.out);

Obviously, the above is no help if you wish to determine whether to use Windows console enabled java.exe versus non-console javaw.exe.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement