Multithreading
Atomic Variables
Learn about lock-free, atomic operations using CPU Compare-And-Swap (CAS) instructions.
Interview: Focuses on Compare-And-Swap (CAS) theory, volatile fields inside Atomic variables, and comparing atomic classes vs synchronized performance.
In high-concurrency systems, acquiring monitor locks incurs scheduling overhead. Atomic Variables (like AtomicInteger, AtomicLong) use CPU-level Compare-And-Swap (CAS) operations to achieve lock-free thread safety.
Core Idea
Atomic classes use CPU instructions to update variables in a single step, bypassing locking mechanisms.
Why It Matters
Lock-free variables avoid thread suspension and context switches, providing extreme throughput under lock contention.
Interview Lens
Focuses on Compare-And-Swap mechanics (expected value vs new value) and the ABA problem.
Compare-And-Swap (CAS) Mechanism
A CAS operation takes three operands: 1. A memory location (V). 2. The expected old value (A). 3. The new value to write (B).
The CPU atomically updates V to B only if the current value at V equals A. Otherwise, the operation fails. Failed threads retry the operation in loops until they succeed (optimistic locking/spinlocks).
Code Walkthrough
This program compares a thread-safe counter using AtomicInteger against a standard unsynchronized integer.
import java.util.concurrent.atomic.AtomicInteger;public class AtomicCounterDemo { private final AtomicInteger atomicCount = new AtomicInteger(0); private int unsafeCount = 0;
public void increment() { atomicCount.incrementAndGet(); // Lock-free atomic increment unsafeCount++; // Unsafe non-atomic increment }
public int getAtomicCount() { return atomicCount.get(); } public int getUnsafeCount() { return unsafeCount; } }
Interview-Relevant Information
Q: What is the ABA problem, and how is it resolved?
Answer: The ABA problem occurs when a thread reads value A, another thread changes A to B and back to A, and the original thread performs a CAS check. The CAS succeeds because the value is still A, but the thread misses the intermediate structural changes. To resolve this, use AtomicStampedReference, which couples a version stamp/integer with the reference.
Quick Checklist
How does CAS differ from intrinsic locks? What is the ABA problem? If yes, you understand atomic variables.
Use Cases
High-performance sequence ID generation.
Lock-free concurrency stats logging inside network loops.
Common Mistakes
Assuming multiple operations on an atomic variable are collectively atomic (e.g. calling get() and set() sequentially is NOT thread-safe; use updateAndGet() instead).
Using Atomic variables in scenarios with high write contention (under extreme contention, CAS spinlocks waste CPU cycles; consider LongAdder instead).