So I’ve got a Java class that implements Runnable. In the run method I’ve got the following code and I don’t fully understand why it works the way it seems to and was hoping someone could explain it to me.
The code is:
public void run() {
Process p = null;
ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true);
p = builder.command("/opt/program/testscript.sh").start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
try {
while ((line = br.readLine()) != null) {
log.info(line);
}
boolean running = true;
while(running) {
p.waitFor();
running = false;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
p.destroy();
}
}
So, the top part is getting the output from the process that’s running and displaying it. The middle part though seems to be where the code waits for the thread to process. As I understand it, the code should stop and wait in the while loop at the p.waitFor() command until the thread finishes, and then the whole thing should end. However, output continues to be displayed while the thread is running so obviously the while loop at the top is still being hit.
Threading has always been my weakest point and clearly I’m just not totally grasping what’s going on here. The code works though so I guess it’s valid. Though perhaps it’s not coded the way it should be? Anyway, help is much appreciated, thanks.
UPDATE
Thanks for the info all. Makes sense that the while(running) loop doesn’t do anything. I will remove it. I added the rest of the code up above that I didn’t provide before to give some more context in case anyone has anything further to add.
The first loop stops when who ever is filling
brcloses it.p.waitFor()indeed waits untilpfinishes. The loop is kind of void since it executes exactly once, so you might as well remove it.Sooo … assuming
pis whats filling up br until it is done and exits, thewaitForwill only have to wait a very short time, possibly not at all.In order to understand more exactly what is going on one would need the code behind
p, of whatever fillsbrand how these things get started.