All topics
library
advanced

Atomic Classes & CAS Operations

Use lock-free thread-safe operations on single variables with AtomicInteger, AtomicReference, and compare-and-swap.

The java.util.concurrent.atomic package provides classes for lock-free, thread-safe operations on single variables. They use Compare-And-Swap (CAS) CPU instructions — no locks, no blocking.

CAS = trying to swap a book on a shelf. You check if 'Java Basics' is still there (expected), grab it, and put 'Java Advanced' in its place (newValue). If someone already swapped it, you notice and try again.

Key Concepts

1
Key classes: - AtomicInteger, AtomicLong: thread-safe int/long with atomic increment, compare-and-set - AtomicBoolean: thread-safe boolean flag - AtomicReference<T>: thread-safe reference update - AtomicIntegerArray, AtomicReferenceArray: atomic operations on array elements - LongAdder, LongAccumulator (Java 8): high-throughput counters optimized for many threads
2
Core operation: compareAndSet(expected, newValue) — atomically sets to newValue if current value equals expected. Returns true if successful, false if another thread changed the value. The caller retries in a loop.
3
CAS advantages over synchronized: - No context switching (no blocking/waking threads) - Better scalability under moderate contention - No deadlock risk
4
CAS disadvantages: - ABA problem: value changes from A→B→A, CAS sees 'A' and succeeds even though the value changed. Use AtomicStampedReference to detect this. - Busy-spinning under high contention wastes CPU. LongAdder solves this by distributing the count across multiple cells.