Interface Clock


public interface Clock
An interface to represent clocks, so that they can be mocked out in unit tests.
  • Method Summary

    Modifier and Type
    Method
    Description
    long
     
    long
    Current value of high resolution time source, in ns.
    long
    waitTillTime(long targetTime)
    Wait until the wall clock reaches at least the given time.
  • Method Details

    • getTimeMillis

      long getTimeMillis()
      Returns:
      Current system time, in ms.
    • nanoTime

      long nanoTime()
      Current value of high resolution time source, in ns.

      This method abstracts the call to the JRE's System.nanoTime() call. As with that method, the value here is not guaranteed to be monotonically increasing, but rather a higher resolution time source for use in the calculation of time intervals. The characteristics of the values returned may very from JVM to JVM (or even the same JVM running on different OSes or CPUs), but in general it should be preferred over getTimeMillis() when calculating time differences.

      Specifically for Linux on x64 architecture, the following links provide useful information about the characteristics of the value returned:

      http://btorpey.github.io/blog/2014/02/18/clock-sources-in-linux/ https://stackoverflow.com/questions/10921210/cpu-tsc-fetch-operation-especially-in-multicore-multi-processor-environment

      TL;DR: on modern (2.6.32+) Linux kernels with modern (AMD K8+) CPUs, the values returned by System.nanoTime() are consistent across CPU cores *and* packages, and provide always increasing values (although it may not be completely monotonic when the system clock is adjusted by NTP daemons using time slew).

      Returns:
      (undocumented)
    • waitTillTime

      long waitTillTime(long targetTime)
      Wait until the wall clock reaches at least the given time. Note this may not actually wait for the actual difference between the current and target times, since the wall clock may drift.
      Parameters:
      targetTime - (undocumented)
      Returns:
      (undocumented)