Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 553
SerCe Avatar asked Jul 15 '18 02:07

SerCe


2 Answers

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:

  • Linux clock_gettime(CLOCK_MONOTONIC) strange non-monotonic behavior
like image 197
Stephen C Avatar answered Sep 18 '22 02:09

Stephen C


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.

like image 29
Sam Avatar answered Sep 21 '22 02:09

Sam