Java Concurrency Interview

Atomics and compare-and-swap question 55 of 180 mid

What is compare-and-swap, and how does AtomicInteger.incrementAndGet use it?

CAS takes an address, the value you expect to find and the value you want to install, and performs the swap atomically only if the expectation holds. On x86 it is lock cmpxchg; on ARM it is a load-linked / store-conditional pair. It returns whether it succeeded.

Conceptually, incrementAndGet reads the current value, computes value plus one, and calls compareAndSet. If another thread got in first, the CAS fails and the whole thing is retried with the new value. That loop is what updateAndGet still does, and what getAndAddInt falls back to. On x86, HotSpot replaces the plain increment with a single lock xadd, which cannot fail, so the retry only exists where the hardware has no fetch-and-add. No lock is ever taken and no thread is ever parked, which is why a failing thread does not block anyone else.

The consequence to state in an interview: CAS is lock-free, not wait-free. The system always makes progress, but a given unlucky thread can retry many times.

cas atomics

Quiz yourself on Atomics and compare-and-swap Suggest a correction