Can nanoTime be non-monotonic?

David Holmes david.holmes at oracle.com
Thu Jun 5 05:08:21 UTC 2025


Hi Pavel,

On 5/06/2025 3:17 am, Pavel Rappo wrote:
> I was reading a book that refers to this 2015 post claiming that
> nanoTime can be non-monotonic:
> https://steveloughran.blogspot.com/2015/09/time-on-multi-core-multi-socket-servers.html
> 
> In fact, I'm not sure what the claim actually is, as the author is a
> bit vague. It's unclear whether they say that they have actually
> observed it, or they just strongly suspect that it's possible.

The article is mainly referring to the unreliable use of the TSC for the 
nanoTime clock on x86 architecture. This has been mostly addressed at 
the hardware level with frequency-invariant TSC, better coordination 
across cores/processors etc. Though virtualization still messes things 
up from time to time.

> Has non-monotonicity ever been observed by hotspot developers? Can it
> be observed on a modern hardware + JVM?

Yes it has been observed many times over the years on different OS, 
different hardware, and importantly different virtualization 
technologies. At different times all of the virtualization technologies 
have "broken" the system clocks in one way or another.

Hotspot relies on the operating system to provide a well behaved clock 
source for nanoTime (and for other timing related functionality). 
Luckily for us the OS clock source support is much better today than 
2015 (and much much better than in 2006 when I wrote my blog article on 
this topic :) [1] ), and the OS tends to deal with many (but not all 
virtualization issues).

At different times we have had logic in hotspot to ensure that nanoTime 
(really the underlying javaTimeNanos in the VM) does not go backwards, 
but with poorly behaving clocks even that has issues as it can cause 
time to appear to freeze until we catch up. Currently only the 
implementation for macOS has a check to stop time from going backwards 
(I don't recall the history on that one).

Cheers,
David

[1] 
https://web.archive.org/web/20160308031939/https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks

> Thanks,
> -Pavel



More information about the hotspot-runtime-dev mailing list