【问题标题】:AtomicInteger incrementationAtomicInteger 增量
【发布时间】:2011-12-15 00:57:47
【问题描述】:

如果AtomicInteger 达到Integer.MAX_VALUE 并增加会怎样?

值会回到零吗?

【问题讨论】:

  • 您可以自己轻松尝试,方法是将整数设置为最大值,然后将其递增。
  • 这个问题+1!我认为堆栈溢出的目的是让我们回答这样的问题,而不是让别人因为问这个问题而感到难过。关键不在于用户是否应该能够自己“弄清楚”。他们确实需要帮助,我们随时为他们提供帮助。
  • 有时边缘情况数学运算的行为是未定义的,并且取决于 JVM,因此您必须阅读文档。这是一个很好的问题。
  • 要确定会发生什么,请使用getAndUpdate()

标签: java integer


【解决方案1】:

由于integer overflow,它环绕到Integer.MIN_VALUE

System.out.println(new AtomicInteger(Integer.MAX_VALUE).incrementAndGet());
System.out.println(Integer.MIN_VALUE);

输出:

-2147483648
-2147483648

【讨论】:

    【解决方案2】:

    浏览源代码,他们只是有一个

    private volatile int value;
    

    和,以及不同的地方,他们从它添加或减去,例如。在

    public final int incrementAndGet() {
       for (;;) {
          int current = get();
          int next = current + 1;
          if (compareAndSet(current, next))
             return next;
       }
    }
    

    所以它应该遵循标准的 Java 整数数学并环绕到 Integer.MIN_VALUE。 AtomicInteger 的 JavaDocs 对此事保持沉默(据我所见),所以我猜这种行为将来可能会改变,但这似乎极不可能。

    如果有帮助的话,有一个 AtomicLong。

    另见What happens when you increment an integer beyond its max value?

    【讨论】:

      猜你喜欢
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      相关资源
      最近更新 更多