A Non-Blocking Process.waitFor()
When calling java.lang.Process.waitFor() the call will block (wait()) until the process actually exits. The waitFor() call is blocking, which is pretty irritating sometimes, for instance when #&%€! wine decides to hang itself, hereby stealing my tomcat execute threads and database connections in production
Well, here’s a quick and dirty solution to creating a non-blocking waitFor() call:
public boolean nonBlockingWaitFor(Process proc, long procMaxTimeoutMillis) throws InterruptedException {
final long TIMESTAMP_BEFORE_EXECUTE = System.currentTimeMillis();
boolean hasExited = false;
while (!hasExited) {
try {
// set/calculate your own granularity of check, which fits your procMaxTimeoutMillis
Thread.sleep(500);
// using the IllegalThreadStateException side-effect of exitValue() if process hasn't exited
proc.exitValue();
hasExited = true;
} catch (IllegalThreadStateException e) {
if (System.currentTimeMillis() > (TIMESTAMP_BEFORE_EXECUTE + procMaxTimeoutMillis)) {
break;
}
}
}
return hasExited;
}
This little block of code makes use of the fact, that Process.exitValue() will throw IllegalThreadStateException if one tries to peek at the exit value before the process has exited.
Is it nice? No!
Does it work? Yes!
July 16, 2010
Tags: Java Posted in: Programming

Leave a Reply