Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

java - Is -System.nanoTime() + System.nanoTime() guaranteed to be >= 0?

Hi all I have a piece of code which looks like this:

public class Test {
    public static void main(String args[]) {
        long a = System.currentTimeMillis(); // line 1
        long b = System.currentTimeMillis(); // line 2
        assert b - a >= 0;

        long y = System.nanoTime(); // line 5
        long z = System.nanoTime(); // line 6
    }
}

So IERS stated that the next leap second is to occur immediately after 30th June 2012 11:59.9.

I was wondering if I'm right to say that if line 1 is run at 0.9 seconds after 30th June 2012 11:59.9 turns 1st July 2012 00:00.0,

And line 2 is run at 0.1 second after line 1,

The result of b - a could be negative ? (-900 milliseconds)

If that's the case, is it true that if line 5 is run at 0.9 seconds after 30th June 2012 11:59.9 turns 1st July 2012 00:00.0,

And line 6 is run at 0.1 second after line 5,

The result of z - y could be negative ? (-900,000,000 nanoseconds?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

System.nanoTime should be monotonically increasing -- if you have two calls to it, A and B, and A happens-before B, then A <= B. But in practice, you can actually observe nanoTime going "backwards."

nanoTime is determined by an internal counter on the CPU whose starting time is essentially arbitrary (which is why it can't be used to determine wall clock time). This can cause a problem in multi-core environment, since one core's internal timer may have a different starting point than another's. Hotspot tries to compensate for this, but it doesn't always succeed, so you can in fact see nanoTime ticking backwards in some situations.

There was a recent discussion about this on the concurrency-interest mailing list. See in particular this email which links to this bug report, and this email which talks about the workaround (which doesn't seem to work, though I'm not sure why). The bug report has a fair amount of detail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...