Is System.nanoTime() consistent across threads?
Asked Answered
E

1

15

I want to count the time elapsed between two events in nanoseconds. To do that, I can use System.nanoTime() as mentioned here. The problem is that the two events are happening in different threads.


Since nanoTime() doesn't return an absolute timestamp but instead can only be used to calculate time differences, I'd like to know if the values I get on the two different threads are consistent with the physical time elapsed between the two events.

Erskine answered 22/4, 2010 at 3:43 Comment(1)
You can can use nanoTime() to calculate the difference from a known time. This can allow you to get a fairly accurate clock. I wouldn't suggest using it for times smaller than a micro-second.Diathesis
M
13

It's supposed to be, but due to buggy kernels or hardware, the answer can be no, at least in some environments.

Manwell answered 22/4, 2010 at 3:58 Comment(3)
Also, I once got into trouble when setting -XX:AggressiveOpts on Sun JVM lead to unreliable values for System.nanoTime().Hilleary
I have no expertise in the matter, but I'll link this highly upvoted answer that suggests this linked blog post is incorrect.Dunston
As of OpenJDK 8u192, there are no known unresolved bugs regarding this. The last one appears to be bugs.openjdk.java.net/browse/JDK-8184271Guerdon

© 2022 - 2024 — McMap. All rights reserved.