简体   繁体   中英

AtomicInteger incrementation

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

Does the value go back to zero?

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

Browing the source code, they just have a

private volatile int value;

and, and various places, they add or subtract from it, eg 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM