Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: set timeout on a certain block of code?

Tags:

java

timeout

Is it possible to force Java to throw an Exception after some block of code runs longer than acceptable?

like image 756
htf Avatar asked Apr 19 '11 10:04

htf


People also ask

How do you add a timeout in Java?

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.


1 Answers

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(); 
like image 134
user2116890 Avatar answered Oct 06 '22 16:10

user2116890