0

Will the below program use 2 different JVMs? One for main program and one for Sample.jar program?

public class Hello {

    public static void main(String args[]) throws Exception {
        Thread.sleep(5000);
        System.out.println("will exec now");

        Process p = Runtime.getRuntime().exec("java -jar Sample.jar");
        while (p.isAlive()) {
            Thread.sleep(5000);
            System.out.println("still alive");
        }

        System.out.println("Done !!");
    }
}
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
user1
  • 45
  • 7
  • That's launching a different process, a separate JVM. – ernest_k Jan 27 '19 at 09:13
  • As a side note, this code may lead to deadlocks, as `Runtime.exec` establishes pipes between the two processes, so when the subprocess expects input or produces more output than the pipe’s buffer can store, it will hang forever. If you do not want to handle the input & output of the subprocess, you can redirect it to the parent’s channels using `Process p = new ProcessBuilder("java", "-jar", "Sample.jar").inheritIO().start();` – Holger Jan 29 '19 at 11:30

1 Answers1

4

One for main program and one for Sample.jar program?

Yes, the java tool (*nix docs, Windows docs) launches a new instance of the JVM, completely unrelated to the running instance¹, just as though you'd run it directly, not via Java code.

In fact, the two JVM instances could even be different versions, if you have multiple installations on the machine (say, Java 9 and Java 10) and you're running this code in one of them (say, Java 9) but the java tool you're calling is for another (say, Java 10). But even if the same version, the two instances are completely unrelated to each other¹.


¹ (other than that the one is a parent process of the other)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks!. Is there a way i can print the JVM information in the code to differentiate it is running in different JVM? – user1 Jan 27 '19 at 09:19
  • @user1 - You can get the process ID, which will be different between the two: https://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id – T.J. Crowder Jan 27 '19 at 09:48