Add timeout to `Runtime.exec()` process in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.io.IOException; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) throws IOException, InterruptedException { String compile = "javac Main.java"; String run = "java Main"; Process compileProcess = Runtime.getRuntime().exec(compile); if (!compileProcess.waitFor(5, TimeUnit.SECONDS)) { compileProcess.destroy(); System.out.println("Compile Timeout Occurred"); System.exit(-1); } // ... Process runProcess = Runtime.getRuntime().exec(run); if (!runProcess.waitFor(15, TimeUnit.SECONDS)) { runProcess.destroy(); System.out.println("Run Timeout Occurred"); System.exit(-1); } // ... System.out.println("Success"); } } |
That’s all about adding timeout to the Runtime.exec() process in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)