SteelReed

Search

Search posts, questions…

ConcurrencyQuestion 6 / 19

Middle

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.

yesno, another thread wroteRead current value vCompute next = v + 1CAS: still equals v?Write next, done

3 points to say:

  1. volatile only gives visibility, count++ still races; AtomicInteger.incrementAndGet() is atomic.
  2. Lock-free is not always faster: under high contention CAS retries a lot, so counters should use LongAdder.
  3. 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.