Atomic variables
AtomicInteger is supposed to be thread-safe.
As per my understanding of atomic integers, it works on the principle of Compare and Swap algorithm.
Compare and swap is atomic at the CPU level.
You can implement an increment operation explicitly with compare and swap:
The compareAndSwap
is guaranteed by the CPU to be atomic (there will be a native implementation of this).
If two threads hit this compareAndSwap
at the same time, only one of them will "win", receiving true
as the result of the compareAndSwap
call, so the loop stops.
The other thread will "lose", and receive false
as the result, and so will go round the loop again: it reads a new value, and then tries the CAS again. If this succeeds (because either no other thread was trying to do it at the same time, or it "won" over another thread), the loop stops; otherwise, it just tries again.
Last updated