The subprocess starts with Java terminations using waitFor, but threads do not terminate.

I use Java ProcessBuilder to run a subprocess, which is another Java program that needs to run in a separate JVM.

I am running two threads to read from stdout and stderr threads from Process, so there is no freeze if the stream buffers are full. A call to the Process.waitFor method returns, but the threads do not terminate.

The code I use looks something like (command - list of lines):

ProcessBuilder pb = new ProcessBuilder(command); final Process p = pb.start(); final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); final ByteArrayOutputStream errStream = new ByteArrayOutputStream(); Thread outputThread = new Thread() { @Override public void run() { try { IOUtils.copy(p.getInputStream(), outStream); } catch (IOException e) { e.printStackTrace(); } }; }; outputThread.start(); Thread errorThread = new Thread() { @Override public void run() { try { IOUtils.copy(p.getErrorStream(), errStream); } catch (IOException e) { e.printStackTrace(); } }; }; errorThread.start(); int returncode = p.waitFor(); outputThread.join(); errorThread.join(); 

If I run something else, like "java -version" or "dir" or something else, the code works fine. I have access to the Java code I'm trying to run, but I never heard you call close () on System.out.

+6
source share
2 answers

Apache commons exec does all this for you. Much easier to do ...

http://commons.apache.org/exec/

+3
source

As I know from this website , you should close all std streams from the Process object yourself. Regardless of whether it is used before or not. This seems very related to the G1 garbage collector (by default with Java 7 afaik), which supports open pipes if they are not explicitly closed, even when the subprocess is complete.

I am not familiar with the internal components, but the code that I posted in my answer to my question works fine on the 24/7 system call of GhostScript and others.

Other SO questions and answers stating that you should close the core of the std-streams process:

0
source

Source: https://habr.com/ru/post/897618/


All Articles