What happens if AtomicInteger
reaches Integer.MAX_VALUE
and is incremented?
Does the value go back to zero?
An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes. Since: 1.5 See Also: Serialized Form.
Integers are object representations of literals and are therefore immutable, you can basically only read them. AtomicIntegers are containers for those values. You can read and set them. Same as asigning a value to variable.
2.1.getAndAdd() – Atomically adds the given value to the current value and returns old value. incrementAndGet() – Atomically increments the current value by 1 and returns new value after the increment. It is equivalent to ++i operation. getAndIncrement() – Atomically increment the current value and returns old value.
Atomic Objects It's also possible to achieve thread-safety using the set of atomic classes that Java provides, including AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization.
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, 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With