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:
isAlive()
checks if an external process is still alivewaitFor(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 runningdestroyForcibly()
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
You must be logged in to post a comment.