2011-12-15 69 views
17

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

该值是否回到零?

+16

您可以轻松地尝试通过设置一个整数到最大值然后递增它。 – Gabe 2011-12-15 00:59:27

回答

32

见自己:

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

输出:

-2147483648 
-2147483648 

看起来它确实包裹到MIN_VALUE。

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?