如果AtomicInteger达到Integer.MAX_VALUE并递增,会发生什么?
这个值会回到零吗?
发布于 2011-12-15 09:09:36
由于integer overflow的缘故,它回绕到Integer.MIN_VALUE
System.out.println(new AtomicInteger(Integer.MAX_VALUE).incrementAndGet());
System.out.println(Integer.MIN_VALUE);输出:
-2147483648
-2147483648发布于 2011-12-15 09:05:06
浏览源代码,他们只有一个
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?
https://stackoverflow.com/questions/8513826
复制相似问题