AtomicInteger incrementation

Browing the source code, they just have a

private volatile int value;

and, and various places, they add or subtract from it, e.g. in

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

So it should follow standard Java integer math and wrap around to Integer.MIN_VALUE. The JavaDocs for AtomicInteger are silent on the matter (from what I saw), so I guess this behavior could change in the future, but that seems extremely unlikely.

There is an AtomicLong if that would help.

see also What happens when you increment an integer beyond its max value?


It wraps around, due to integer overflow, to Integer.MIN_VALUE:

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

Output:

-2147483648
-2147483648

Tags:

Java

Integer