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.

Community
  • 1
  • 1
agentofuser
  • 8,987
  • 11
  • 54
  • 85
  • 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. – Peter Lawrey Apr 22 '10 at 06:37

1 Answers1

13

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

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
  • 1
    Also, I once got into trouble when setting `-XX:AggressiveOpts` on Sun JVM lead to unreliable values for System.nanoTime(). – Binil Thomas Apr 22 '10 at 04:10
  • I have no expertise in the matter, but I'll link [this highly upvoted answer](http://stackoverflow.com/a/4588605/1031507) that suggests this linked blog post is incorrect. – Paul Whalen Feb 27 '15 at 19:38
  • 1
    As of OpenJDK 8u192, there are no known unresolved bugs regarding this. The last one appears to be https://bugs.openjdk.java.net/browse/JDK-8184271 – leventov Feb 04 '19 at 03:30