简体   繁体   中英

time4j is not producing monotonic time in long since epoch

I'm trying to produce monotonic time in long since epoch using time4j v5.6 using below test code

But output is not expected. Did I miss any initialization of the library? My objective is to produce monotonic time but don't need high precision as this can be executed on client side either linux/windows

import net.time4j.SystemClock;

import java.time.Instant;

public class MonotonicClock {
    public static void main(String[] args) {
        SystemClock systemClock = SystemClock.MONOTONIC;
        long t1 = systemClock.currentTimeInMicros() * 1000;
        boolean failed = false;
        for (int i = 0; i < 1000_000; i++) {
            long t2 = systemClock.currentTimeInMicros() * 1000;
            if (t2 < t1) {
                System.out.println(Instant.ofEpochSecond(0, t2) + "<" + Instant.ofEpochSecond(0, t1));
                failed = true;
            }
            t1 = t2;
        }

        if(failed) {
            System.err.println("Test Failed");
        }else {
            System.out.println("Test Passed");
        }
    }
}

The Clock SystemClock.MONOTONIC is ultimately based on System.nanoTime() , see the source code . Latter one should be monotonic, and at least the handling of rare leap seconds is safely monotonic here, but it might happen to be not monotonic on some multi-core platforms where the JVM has difficulties to switch between the cores to form a consistent result of calling System.nanoTime() . See also the related SO-post with more useful links to the debate about the monotonicity of System.nanoTime() .

A workaround could be to introduce a new constant SystemClock.MONOTONIC_ENFORCED which deploys a CAS-algorithm (based on java.util.concurrent.atomic.AtomicLong ) to compare the actual nano-time with the previous one (with possible performance penalty). Let me know if you need this feature in the next release of Time4J.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM