Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a loop in getAndIncrement() in Java AtomicInteger?

the source code of getAndIncrement is:

public final int getAndIncrement() {
   for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return current;
    }
}

I don't understand why there is a loop. If some other threads have changed the value, then how can it be atomic?

let's say the value is 5, then I call getAndIncrement(), we expect it to be 6, but at the same time some other threads have changed the value to 6, then getAndIncrement() will make the value to 7, which is not expected.

Where am I wrong?

like image 270
Lily Avatar asked Mar 09 '23 15:03

Lily


1 Answers

The loop will keep going until it manages to do the get(), the +1, and the compareAndSet without any other thread getting in a compareAndSet first. If another thread does get a compareAndSet in, then this thread's compareAndSet will fail, and the loop will retry.

The end result is that each call to getAndIncrement() will result in exactly one increment to the value. If the value is initially 5, and two threads call getAndIncrement(), then one will return 6 and the other will return 7.

Put another way: one of them will appear to happen fully after the other, which is what "atomic" means.

like image 85
yshavit Avatar answered Mar 12 '23 23:03

yshavit