Is it possible to force Java to throw an Exception after some block of code runs longer than acceptable?
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.
Here's the simplest way that I know of to do this:
final Runnable stuffToDo = new Thread() { @Override public void run() { /* Do stuff here. */ } }; final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future future = executor.submit(stuffToDo); executor.shutdown(); // This does not cancel the already-scheduled task. try { future.get(5, TimeUnit.MINUTES); } catch (InterruptedException ie) { /* Handle the interruption. Or ignore it. */ } catch (ExecutionException ee) { /* Handle the error. Or ignore it. */ } catch (TimeoutException te) { /* Handle the timeout. Or ignore it. */ } if (!executor.isTerminated()) executor.shutdownNow(); // If you want to stop the code that hasn't finished.
Alternatively, you can create a TimeLimitedCodeBlock class to wrap this functionality, and then you can use it wherever you need it as follows:
new TimeLimitedCodeBlock(5, TimeUnit.MINUTES) { @Override public void codeBlock() { // Do stuff here. }}.run();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With