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

This question is not intended to attack System.nanoTime()

. I realize this is a surprisingly tricky method to use correctly.

What ways can be accessed by System.nanoTime()

returning the same value between calls? Example: Multiple threads call System.nanoTime()

and receive the same value.

I am surprised how often I see this happening in my codebase when running tests on Windows. We use nanoTime

to sort events that arrive across multiple threads. Perhaps this is just a Windows problem, and Linux monotonous hours are more granular.

Literature:

+3


source to share


1 answer


To explain why you are getting the same value, read the documentation a bit:

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how often the value changes) - there is no guarantee, except that the resolution is at least that is, currentTimeMillis ().

Your computer might run out of clock resolution, so it might be a good chunk of time to nanoTime

return the same number.



Regarding your question

In what ways can System.nanoTime () be called, returning a value between calls?

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

+4


source







All Articles