How to handle when System.nanoTime() returns the same value between calls?

1.2k Views Asked by At

This question is not intended as an attack upon System.nanoTime(). I realize it is a surprisingly tricky method to use correctly.

What are some ways to deal with System.nanoTime() returning the same value between calls? Example: Multiple threads call System.nanoTime() and get the same value.

I am surprised how often I see this happen in my code base when running tests on Windows. We use nanoTime to sort events that arrive across multiple threads. Perhaps this is only a Windows issue and the Linux monotonic clock is more granular.

References:

1

There are 1 best solutions below

6
On BEST ANSWER

To explain why you're getting the same value, read the documentation a bit more closely:

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().

Your computer may not have enough clock resolution, so there could be a good chunk of time where nanoTime will return the same number.

As for your question

What are some ways to deal with System.nanoTime() returning the same value between calls?

I would suggest using some sort of an atomic counter, as Claudio Corsi suggests.