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:
To explain why you're getting the same value, read the documentation a bit more closely:
Your computer may not have enough clock resolution, so there could be a good chunk of time where
nanoTimewill return the same number.As for your question
I would suggest using some sort of an atomic counter, as Claudio Corsi suggests.