I have a method I am using to execute a command on the local host. I\'d like to add a timeout parameter to the method so that if the command being called doesn\'t finish in
There are various ways to do this, but I'd consider using an Executor-- it just helps you encapsulate passing the exit value or exception from the thread back to the original caller.
final Process p = ...
Callable call = new Callable() {
public Integer call() throws Exception {
p.waitFor();
return p.exitValue();
}
};
Future ft = Executors.newSingleThreadExecutor().submit(call);
try {
int exitVal = ft.get(2000L, TimeUnit.MILLISECONDS);
return exitVal;
} catch (TimeoutException to) {
p.destroy();
throw to;
}
I think you can't get round the race condition whereby the wait times out, and then process terminates just before you call destroy().