AtomicInteger递增

时间:2011-12-15 00:57:48

标签: java integer

如果AtomicInteger到达Integer.MAX_VALUE并递增,会发生什么?

值是否回归零?

2 个答案:

答案 0 :(得分:39)

亲眼看看:

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

输出:

-2147483648
-2147483648

看起来 换行到MIN_VALUE。

答案 1 :(得分:6)

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

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?