Let me start from the end of your question. Yes in case value is greater than 2^63-1 the value will overflow. Common implementation of an overflow is that the least significant representable bits of the result are stored; value will wrap (you can see at the bottom of my post about overflow for reference)
Sequence is like: 2^63-2, 2^63-1, -2^63, -(2^63-1) ...
Now looking back at Javadoc I agree that the explanation about using comparison is confusing and that naturally we would try to compare t1 > t0
to validate if t1
happened after t0
. You are partially right. Though I don't think it is a typo but it is not explained correctly. I think it should say:
For two values t0
and t1
(where t1 is captured after t0), you should not use t1 < t0
(to check for false
) but rather t1 - t0 < 0
, similarly you should not use t1 > t0
(to check for true
) but rather t1 - t0 > 0
Or to formalise it:
For two 'nano' values t0
and t1
, where t1
is captured after t0
following stands: (t1 - t0 > 0) == true
as long as the period between t1
and t0
is <= 2^63 ns.
Why? Because even when t1
overflows (so it is negative), the result t1 - t0
will also be negative but, it will be less than -2^64 and it will 'overflow back' to positive value! .
This stands as long as the condition about the distance between t0
and t1
is met! In case the distance is larger than 2^64 e.g: for t0 = 1; t1 = -(2^64-2)
, subtraction result would be: t1 - t0 = -(2^64-1)
so the specified condition (t1 - t0 > 0
) will give incorrect result.
Right?:)
On overflow
For the sake of explanation lats assume a type that is stored using 8 bits (instead of 64 used by long), so binary to decimal representation is:
0000 0000 => 0
0000 0001 => 1 (2^0)
0000 0010 => 2 (2^1 + 2^0)
...
1111 1111 => 255 (2^7 + 2^6 + ... + 2^1)
now next number is naturally when you would increment by 1.
adding 1 to binary 1111 1111 will produce 1 0000 0000
(1) 0000 0000 => -256 !!!
typically the overflown bit on a position 8 will represent a (negative-weight) sign bit
first following value is adding 1 to most-right position
(1) 0000 0001 => -256 + 2^0 = -255
(1) 0000 0010 => -256 + 2^1 = -254
(1) 0000 0011 => -256 + 2^1 + 2^1 = -253
...
you get the picture
The origin of this is in the underlying hardware registry implementation which relies on binary values.
You can read more detailed explanation for instance here: http://www.allaboutcircuits.com/textbook/digital/chpt-2/binary-overflow/