Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AtomicInteger incrementation

Tags:

java

integer

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

Does the value go back to zero?

like image 697
destiny Avatar asked Dec 15 '11 00:12

destiny


People also ask

What is AtomicInteger and when to use?

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.

What is difference between Integer and AtomicInteger?

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.

How do you initialize AtomicInteger in Java?

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.

Is AtomicInteger thread-safe?

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.


2 Answers

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 
like image 122
Bohemian Avatar answered Sep 22 '22 13:09

Bohemian


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?

like image 21
user949300 Avatar answered Sep 21 '22 13:09

user949300