[concurrency-interest] deadline and long overflow

Martin Buchholz martinrb at google.com
Wed Apr 20 12:25:39 EDT 2016


On Wed, Apr 20, 2016 at 6:57 AM, Peter Veentjer <alarmnummer at gmail.com> wrote:
> Thanks for the replies.
>
> The question is not about waiting given amount of time; but the calculation
> of the deadline itself which can become negative due to overflow. So imagine
> you call:
>
> queue.poll(Long.MAX_VALUE, NANOS)
>
> then the deadline will be < 0 due to overflow.
>
> The question is if it can happen that a blocking call fails with a timeout,
> perhaps immediately due to this deadline becoming negative. I made some
> small examples and it seems to self correct like David suggested but it
> feels a bit funny.

All of the time handling code in j.u.concurrent is overflow-aware.
It's not really overflow, it's "wraparound".  It's safe because it's
java, not C.  As long as all of the code that handles nanotime values
follows the advice in the javadoc
https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--
everything is fine.

To compare two nanoTime values


 long t0 = System.nanoTime();
 ...
 long t1 = System.nanoTime();
one should use t1 - t0 < 0, not t1 < t0, because of the possibility of
numerical overflow.

It's hard to test that we haven't made a mistake somewhere, though.


More information about the Concurrency-interest mailing list