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?
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:
There can be problems with some old CPU chips; e.g. https://bugzilla.redhat.com/show_bug.cgi?id=1499480
It is not supported for some (all?) versions of Cygwin.
It is not supported for some (all?) versions of uCLibc on ARM.
It is also possible for CLOCK_MONOTONIC
to be supported but buggy:
Is it reasonable to assume that CLOCK_MONOTONIC clock is available on all modern Linux servers?
I can only comment on this question. Yes, it's reasonable that all production-grade systems you use will have a monotonic clock that Linux knows how to access. This is also true of virtual and container servers.
Good engineering dictates you put a check in for this and error-out if an assumption is broken, but I would count on this at design-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With