Java.Multithreading.How CAS works under the hood and how it helps in sychronization ?

🔁 What is CAS (Compare-And-Swap)?

CAS is a hardware-level atomic operation used to implement lock-free synchronization.

It works like this:

  1. Read the current value of a variable (expected).
  2. Compare it to an expected value.
  3. If it matches, swap it with a new value.
  4. If it doesn’t, do nothing — try again (typically in a loop).

✅ In Java:

AtomicInteger atomic = new AtomicInteger(5);
boolean success = atomic.compareAndSet(5, 6); // returns true and sets value to 6

🔬 Under the Hood (JVM & CPU)

At the CPU level, CAS is supported by instructions like:

  • CMPXCHG on x86
  • LDREX/STREX on ARM

These are atomic — meaning:

No other thread can interfere between the compare and the swap.

In Java, the JVM uses these instructions via the Unsafe class or VarHandle internally.


⚙️ Example: CAS-based increment

Imagine atomic.incrementAndGet() — it’s like this:

int oldValue, newValue;
do {
    oldValue = atomic.get();
    newValue = oldValue + 1;
} while (!atomic.compareAndSet(oldValue, newValue));

This loop will keep retrying until it succeeds.

💡 How CAS Helps in Synchronization

FeatureHow CAS Helps
✅ AtomicityOne-thread-only updates via hardware support
✅ Lock-freeNo need for synchronized or locks
✅ High performanceBetter in high-contention environments
❌ No blockingThreads spin instead of waiting

Instead of blocking other threads (like with synchronized), CAS allows multiple threads to try simultaneously — but only one wins.

🧠 CAS vs Synchronized

FeatureCASsynchronized
Blocking❌ No✅ Yes (waits for lock)
OverheadLow (on success)High (context switching)
StarvationPossibleLess likely (depends on fairness)
Use caseCounters, queues, stacksCritical sections with shared state

⚠️ Downsides of CAS

ProblemDescription
ABA ProblemValue changes from A → B → A — looks unchanged
CPU SpinningMay retry endlessly in high contention
Limited OperationsOnly works for single variables or pointers

✅ JVM Support for CAS

  • Atomic* classes (AtomicInteger, AtomicReference)
  • VarHandle (since Java 9 — low-level alternative to Unsafe)
  • StampedLock and LongAdder internally use CAS for high perf

🔄 Summary

ConceptCompare-And-Swap (CAS)
What it doesAtomically updates a value if unchanged
Hardware-supportedYes, via CPU instructions
Java usagecompareAndSet(), incrementAndGet()
BenefitsLock-free synchronization, high performance
LimitationsABA problem, retry loops, not multi-field safe
This entry was posted in Без рубрики. Bookmark the permalink.