destiny
destiny

Reputation: 1852

AtomicInteger incrementation

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

Does the value go back to zero?

Upvotes: 31

Views: 22161

Answers (2)

Bohemian
Bohemian

Reputation: 424983

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

Upvotes: 55

user949300
user949300

Reputation: 15729

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?

Upvotes: 8

Related Questions