Search code examples
javalinuxtimeclockgettimeofday

In what cases CLOCK_MONOTONIC might not be available


In Java System.nanoTime()'s monotonic implementation on Linux relies on the fact that CLOCK_MONOTONIC is available on the OS. If it's not available, it falls back to gettimeofday which can result in getting a negative time interval when the interval is measured using nanoTime. For instance, the following test might fail.

long t1 = System.nanoTime();
long t2 = System.nanoTime();
assert t2 >= t1

In what cases CLOCK_MONOTONIC might not be available on a server? Is it reasonable to assume that CLOCK_MONOTONIC clock is available on all modern Linux servers?


Solution

  • Is it reasonable to assume that CLOCK_MONOTONIC clock is available on all modern Linux servers?

    Yes. It is reasonable to assume that.

    From the wording of the gettime manual entry, we can infer that really old versions of glibc do not support CLOCK_MONOTONIC. (I am still trying to figure out how old ... but probably when glibc claimed POSIX 1003.1 compliance.)

    CLOCK_MONOTONIC was specified (at least) in IEEE Std 1003.1, 2004 Edition, though it remains possible for a compliant libc implementation to not support CLOCK_MONOTONIC.

    The Linux kernel source code has had support for a CLOCK_MONOTONIC clock at least since Linux 3.0 (2011).

    From other sources, it also depends on how your system's glibc was built. (When built with "emulated timers", CLOCK_MONOTONIC is not supported.)

    Here are some cases where it is not supported:


    It is also possible for CLOCK_MONOTONIC to be supported but buggy: