AtomicInteger递增

des*_*iny 26 java integer

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

价值是否会回归零?

Boh*_*ian 44

你自己看:

System.out.println(new AtomicInteger(Integer.MAX_VALUE).incrementAndGet());
System.out.println(Integer.MIN_VALUE);
Run Code Online (Sandbox Code Playgroud)

输出:

-2147483648
-2147483648
Run Code Online (Sandbox Code Playgroud)

看起来它确实换到MIN_VALUE.


use*_*300 6

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

private volatile int value;
Run Code Online (Sandbox Code Playgroud)

和,以及各种地方,他们增加或减少它,例如在

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

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

有一个AtomicLong,如果这会有所帮助.

另请参见 当您将整数增加到超出其最大值时会发生什么?