What is CAS? How do the Atomic classes work, and how do they differ from volatile?
Short answer
CAS (compare-and-swap) is an atomic CPU instruction: "if the value equals what I expect, write the new one, otherwise report failure". Atomic* classes = a volatile field + a CAS retry loop, so they give visibility plus atomic read-modify-write without a lock.
3 points to say:
volatileonly gives visibility,count++still races;AtomicInteger.incrementAndGet()is atomic.- Lock-free is not always faster: under high contention CAS retries a lot, so counters should use
LongAdder. - ABA: the value changes A → B → A and CAS cannot tell; fix it with a version (
AtomicStampedReference).
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.