简体   繁体   中英

Executing jar files sequentially from inside a Java program

I want to execute multiple jar files sequentially by passing I/O and reading the output from them from a single Java program. I used this below code to invoke my jar inside my java code. This is leading to multiple JVM instances and the jar execution is not completing until I stop the execution of my main java program.

Process pb = Runtime.getRuntime().exec("java -jar path/to/jar");
pb.waitFor();
BufferedReader ib = new BufferedReader(new InputStreamReader(pb.getErrorStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(pb.getInputStream()));

System.out.println(in.readLine());

My ideal sequence of execution is:

  • Main java (starts)
  • JAR 1 (starts and completed)
  • JAR 2 (starts and completed)
  • Jar n ----
  • Main Java (stops)

My knowledge is limited in multiprocessing that is going on with my current code. Please help me understand how it works and how can I achieve the scenario I intend to.

As soon as the subprocess produces more output than the pipe's buffering capability, it will be blocked until the initiating process reads the data. When you are waiting for the end of the subprocess before reading anything, this may lead to a deadlock.

Since you are only reading the output to reprint it to the console (or generally, write to stdout), you may use ProcessBuilder to tell it not to use a pipe, but connect the subprocess' stdio to your process' stdio:

Process pb = new ProcessBuilder("java", "-jar", "path/to/jar").inheritIO().start();
pb.waitFor();

Then you don't need to do anything to transfer the subprocess' output to your process' output and there's no deadlock potential.

inheritIO() does the magic. It's a short-hand for .redirectInput(Redirect.INHERIT) .redirectOutput(Redirect.INHERIT) .redirectError(Redirect.INHERIT) . These redirect… calls also can be used for configuring the individual channels to use a pipe or read from/ write to a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM