by Uwe B. Meding

Starting an external process in Java is a fairly straightforward task. Managing the resources of the external process is a different matter altogether and not as obvious as it looks – they have a tendency to dangle. They are easy to start but hard to control once they are running or have completed.

Java 8 adds a several new methods to the Process class:

  1. isAlive() checks if an external process is still alive
  2. waitFor(long timeout, TimeUnit unit) is a new method that provides a timeout guard. The return value indicates if the process has finished or is still presumed running
  3. destroyForcibly() kills an external process and possibly locked resources much better than previous versions
ProcessBuilder pb = new ProcessBuilder();
pb.redirectErrorStream(true);
pb.command("/bin/ls", "-l");
Process p = pb.start();
try {
  if (p.waitFor(1, TimeUnit.SECONDS)) {
    // Analyze the process output
  } else {
    // Process took longer than expected
  }
} finally {
  if (p.isAlive()) {
    p.destroyForcibly();
  }
}

Leave a Reply