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?
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.
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