This post will discuss how to add timeout to the Runtime.exec() process in Java.

Every Java application has a single instance of the Runtime class, and its current instance can be obtained using the Runtime.getRuntime() method. The Runtime.exec(command) method is often used to run a command in the underlying environment.

 
However, if the subprocess doesn’t terminate in a desired amount of time, it is sometimes required to forcibly terminate the subprocess and resume the program execution. Starting with Java 8, you can use the waitFor() method to add a timeout to the Runtime.exec() process. The waitFor() method causes the current thread to wait until the subprocess represented by this Process object has terminated, or the specified waiting time elapses.

The signature of waitFor() method is: waitFor(long timeout, TimeUnit unit). It returns true if the subprocess is terminated normally and false if the waiting time elapsed before the subprocess has exited. If the timeout happens, you can forcibly terminate the subprocess using the destroy() method.

 
To demonstrate, consider the following code, which adds a 5-second timeout to compile and run command.

Download Code

That’s all about adding timeout to the Runtime.exec() process in Java.