-System.nanoTime() + System.nanoTime() 是否保证 >= 0? [英] Is -System.nanoTime() + System.nanoTime() guaranteed to be >= 0?

查看:32
本文介绍了-System.nanoTime() + System.nanoTime() 是否保证 >= 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
    }
}

所以 IERS 表示下一个闰秒将立即发生2012 年 6 月 30 11:59.9 之后.

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

我想知道如果第 1 行在 30th 2012 年 6 月 11:59.91<之后的 0.9 秒运行,我是否正确sup>st 2012 年 7 月 00:00.0,

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,

第 2 行在第 1 行之后的 0.1 秒处运行,

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

b - a 的结果可能是 negative 吗?(-900 毫秒)

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

如果是这样,那么如果第 5 行在 30th June 2012 11:59.91 后的 0.9 秒运行,是否属实?st 2012 年 7 月 00:00.0,

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,

第 6 行在第 5 行之后的 0.1 秒处运行,

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

z - y 的结果可能是 negative 吗?(-900,000,000 纳秒?)

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

推荐答案

System.nanoTime 应该单调递增——如果你有两次调用它,AB,以及 A 发生在 B 之前,然后 A <= B.但在实践中,您实际上可以观察到 nanoTime 倒退".

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 由 CPU 上的内部计数器确定,其开始时间基本上是任意的(这就是它不能用于确定挂钟时间的原因).这可能会在多核环境中导致问题,因为一个内核的内部计时器可能与另一个内核的起始点不同.Hotspot 尝试对此进行补偿,但并不总是成功,因此您实际上可以看到 nanoTime 在某些情况下会倒退.

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.

这篇关于-System.nanoTime() + System.nanoTime() 是否保证 >= 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆