views:

876

answers:

2

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.

+5  A: 

You could wrap the call in a FutureTask and use the timeout version of get().

See http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html

gommo
FutureTask isn't itself asynchronous, is it? On its own it just does things synchronously, you need to combine it with an Executor to egt asynch behaviour.
skaffman
Yep you need an executor like what you coded
gommo
+5  A: 

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
} finally {
   future.cancel(); // may or may not desire this
}

If the future.get doesn't return in 5 seconds, it throws an exception. See javadoc for more detail.

skaffman
The blocking method will continue to run even after the timeout, right?
Ivan Dubrov
That depends on future.cancel. Depending on what the blocking method is doing at the time, it may or may not terminate.
skaffman
tested and worked here.
Jus12