Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call some blocking method with a timeout in Java?

Is there a standard nice way to call a blocking method with a timeout in Java? I want to be able to do:

// call something.blockingMethod(); // if it hasn't come back within 2 seconds, forget it 

if that makes sense.

Thanks.

like image 327
jjujuma Avatar asked Jul 22 '09 10:07

jjujuma


People also ask

How do you do a timeout in Java?

The java. lang. Object. wait(long timeout) causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

How do you handle timeout exception in Java?

Blocking operations for which a timeout is specified need a means to indicate that the timeout has occurred. For many such operations it is possible to return a value that indicates timeout; when that is not possible or desirable then TimeoutException should be declared and thrown.

How do I stop a Java method from running?

Exit a Java Method using Returnexit() method in java is the simplest way to terminate the program in abnormal conditions. There is one more way to exit the java program using return keyword. return keyword completes execution of the method when used and returns the value from the function.


1 Answers

You could use an Executor:

ExecutorService executor = Executors.newCachedThreadPool(); Callable<Object> task = new Callable<Object>() {    public Object call() {       return something.blockingMethod();    } }; Future<Object> future = executor.submit(task); try {    Object result = future.get(5, TimeUnit.SECONDS);  } catch (TimeoutException ex) {    // handle the timeout } catch (InterruptedException e) {    // handle the interrupts } catch (ExecutionException e) {    // handle other exceptions } finally {    future.cancel(true); // may or may not desire this } 

If the future.get doesn't return in 5 seconds, it throws a TimeoutException. The timeout can be configured in seconds, minutes, milliseconds or any unit available as a constant in TimeUnit.

See the JavaDoc for more detail.

like image 99
skaffman Avatar answered Sep 25 '22 00:09

skaffman