Controlling OS Processes - Java Runtime.exec()

Launching an OS process from within your code is right there with JNI calls – it’s something you do half-knowing there’s a good chance you’re going to get some unexpected results and some really bad exceptions down the line.
Even so, it’s a necessary evil. But processes have another nasty angle to them - they have a tendency to dangle. The problem with launching process from within Java code so far has been that is was hard to control a process once it was launched.
To help us with this Java 8 introduces three new methods in the Process class -
  1. destroyForcibly - terminates a process with a much higher degree of success than before.
  2. isAlive tells if a process launched by your code is still alive.
  3. A new overload for waitFor() lets you specify the amount of time you want to wait for the process to finish. This returns whether the process exited successfully or timed-out in which case you might terminate it.
Two good use-cases for these new methods are -
  • If the process did not finish in time, terminate and move forward:
if (process.wait(MY_TIMEOUT, TimeUnit.MILLISECONDS)){
       //success! }
else {
    process.destroyForcibly();
}
  • Make sure that before your code is done, you're not leaving any processes behind. Dangling processes can slowly but surely deplete your OS.
for (Process p : processes) {
       if (p.isAlive()) {
             p.destroyForcibly();
       }
}

Comments

Popular posts from this blog

WMI Static Port configuration

Optimizing your JVM for Best Performance

How do I disable FOREIGN KEY checking for the time of database schema migration?