All other responses are correct but it can be made more robust and efficient using FutureTask.
For example,
private static final ExecutorService THREAD_POOL
= Executors.newCachedThreadPool();
private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit)
throws InterruptedException, ExecutionException, TimeoutException
{
FutureTask<T> task = new FutureTask<T>(c);
THREAD_POOL.execute(task);
return task.get(timeout, timeUnit);
}
try {
int returnCode = timedCall(new Callable<int>() {
public int call() throws Exception
{
java.lang.Process process = Runtime.getRuntime().exec(command);
return process.waitFor();
}, timeout, TimeUnit.SECONDS);
} catch (TimeoutException e) {
// Handle timeout here
}
If you do this repeatedly, the thread pool is more efficient because it caches the threads.