Question

Is it safe to supply a negative timeout to java.util.concurrent.Future.get(long, TimeUnit)? The documentation says

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Does this imply that it will work with negative values, or does this statement only cover the non-negative cases? The behaviour I would expect would be to return the result if it is available or timeout immediately otherwise. This situation may occur, if we want to calculate the timeout for an absolute point in time and this has already passed. Of course I can use max{timeout, 0}, but is this really necessary? Tests in my enviroment showed it worked, but is this guaranteed? https://stackoverflow.com/questions/9332904/behavior-of-future-get-with-0-timeout states that this should be the case for a 0 timeout.

Or to put the question in other words: Assume the result of the Future is available. Would an implementation of Future be non compliant, if get(long, TimeUnit) called with a negative timeout would do something else than returning this result?

Was it helpful?

Solution

It is impossible to wait "at most" some time; the only theoretical guarantee is that the wait time will be no less than some number. This is in fact specified in the JLS. Therefore the wording must be read as follows:

Let t be the given time to wait, and let u be the time this method actually spent before returning control to the caller. If and only if u < t, the return value of the method call is guaranteed to be the return value of the Future.

Given the above, a negative t is fully in order and all values <= 0 should behave exactly the same.

Still, an implementation could conceivably throw an exception for a negative wait time and have a weak excuse for doing so. If your code ever failed due to such an exception, you could start a hot dispute with the authors of said Future implementation. If that ever happened, there is really nothing an answer on Stack Overflow can do to prevent it.

If you subsequently went to court to settle the responsibility for damages, and are interested in the outcome of such a lawsuit, then I believe that concern is beyond the realms of Stack Overflow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top