Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How does compare-and-swap (CAS) work in atomic classes?
CAS is a single atomic CPU instruction (like cmpxchg on x86) that takes a memory location, an expected value, and a new value. It compares the current value at that location to the expected value; if they match, it atomically writes the new value and reports success, and if they don't match, it does nothing and reports failure, all without ever taking a lock.
AtomicInteger counter = new AtomicInteger(0); int oldVal, newVal; do { oldVal = counter.get(); newVal = oldVal + 1; } while (!counter.compareAndSet(oldVal, newVal)); // retry if another thread beat us
Classes like AtomicInteger, AtomicLong, and AtomicReference use this pattern internally: read the current value, compute the new one, then try to install it with CAS, looping back to retry if another thread changed the value in between.
This is called optimistic concurrency control: instead of blocking other threads out with a lock, each thread assumes no conflict will happen and just retries on the rare occasion one does. It scales very well under low-to-moderate contention but can spin repeatedly and waste CPU when many threads contend for the same variable at once.
More Related questions...