Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of future.get with 0 timeout

Can anyone point me to some documentation that makes clear that a 'Future.get` with a timeout of 0 will not wait?

The API docs for java.util.concurrent.Future does not make explicit the behavior of future.get(0, unit). Standing on its own, the statement "Waits if necessary for at most the given time..." implies this invocation will not wait at all, but given the long-standing behavior of Object.wait(0) (infinite wait), I'm nervous to depend on a "no wait" behavior of future.get(0, unit)

Scanning the source of some JDK-provided classes (viz. FutureTask) I see that this particular implementation of Future does not wait when the timeout is 0.

I'd like to be able to say

   long timeout = Math.max(until - now, 0);
   return future.get(timeout, TimeUnit.MILLISECONDS);

but I'm nervous about a Future implementing that as an infinite wait, so instead, I've explicitly coded it the way I would expect it to work:

   long timeout = Math.max(until - now, 0);
   if(timeout > 0 || future.isDone()){
      return future.get(timeout, TimeUnit.MILLISECONDS);
   } else {
      throw TimeoutException();
   }
like image 284
mwhidden Avatar asked Feb 17 '12 17:02

mwhidden


1 Answers

Waits if necessary for at most the given time…

Waiting for at most zero time units is not waiting at all. That's not an implicit hint, it's an explicit guarantee.

like image 175
erickson Avatar answered Oct 02 '22 13:10

erickson