🔁 What is CAS (Compare-And-Swap)?
CAS is a hardware-level atomic operation used to implement lock-free synchronization.
It works like this:
- Read the current value of a variable (
expected). - Compare it to an expected value.
- If it matches, swap it with a new value.
- 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:
CMPXCHGon x86LDREX/STREXon 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
| Feature | How CAS Helps |
|---|---|
| ✅ Atomicity | One-thread-only updates via hardware support |
| ✅ Lock-free | No need for synchronized or locks |
| ✅ High performance | Better in high-contention environments |
| ❌ No blocking | Threads 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
| Feature | CAS | synchronized |
|---|---|---|
| Blocking | ❌ No | ✅ Yes (waits for lock) |
| Overhead | Low (on success) | High (context switching) |
| Starvation | Possible | Less likely (depends on fairness) |
| Use case | Counters, queues, stacks | Critical sections with shared state |
⚠️ Downsides of CAS
| Problem | Description |
|---|---|
| ABA Problem | Value changes from A → B → A — looks unchanged |
| CPU Spinning | May retry endlessly in high contention |
| Limited Operations | Only works for single variables or pointers |
✅ JVM Support for CAS
Atomic*classes (AtomicInteger,AtomicReference)VarHandle(since Java 9 — low-level alternative toUnsafe)StampedLockandLongAdderinternally use CAS for high perf
🔄 Summary
| Concept | Compare-And-Swap (CAS) |
|---|---|
| What it does | Atomically updates a value if unchanged |
| Hardware-supported | Yes, via CPU instructions |
| Java usage | compareAndSet(), incrementAndGet() |
| Benefits | Lock-free synchronization, high performance |
| Limitations | ABA problem, retry loops, not multi-field safe |