30

What happens if AtomicInteger reaches Integer.MAX_VALUE and is incremented?

Does the value go back to zero?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
destiny
  • 1,802
  • 3
  • 16
  • 18
  • 17
    You can easily try this yourself by setting an integer to the maximum value and then incrementing it. – Gabe Dec 15 '11 at 00:59
  • 14
    +1 for this question! I think the point of Stack overflow is for us to answer questions like this and not make someone feel bad for asking the question. The point is not whether or not a user should be able to "figure it out" themselves. They legitimately need help and we are here to provide it. – Mike Pone Feb 16 '12 at 16:04
  • 1
    Sometimes the behavior of edge case math operations are undefined and depend on the JVM, so you have to read the docs. It's a great question. – Nate Glenn Jun 22 '17 at 08:11
  • To be sure what would happen, use [getAndUpdate()](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#updateAndGet-java.util.function.IntUnaryOperator-) – Trần Hoàn Nov 22 '21 at 08:53

2 Answers2

54

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
Bohemian
  • 412,405
  • 93
  • 575
  • 722
8

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?

Community
  • 1
  • 1
user949300
  • 15,364
  • 7
  • 35
  • 66