Mastery
Mastery/Java/E. Concurrency
T2 · intermediate depth

Atomic classes (AtomicInteger, CAS) vs synchronized for simple counters

AtomicInteger/AtomicLong give you lock-free, thread-safe compound operations (incrementAndGet, compareAndSet) built on the CPU's native compare-and-swap instruction -- correct under concurrent access without ever blocking a thread, which is typically faster than synchronized for simple counter-style state under contention.

java
import java.util.concurrent.atomic.AtomicInteger;

AtomicInteger atomicCounter = new AtomicInteger(0);
int nThreads = 8, iterations = 50_000;

Thread[] threads = new Thread[nThreads];
for (int i = 0; i < nThreads; i++) {
    threads[i] = new Thread(() -> {
        for (int j = 0; j < iterations; j++) atomicCounter.incrementAndGet();
    });
}
for (Thread t : threads) t.start();
for (Thread t : threads) t.join();

int expected = nThreads * iterations;
System.out.println("expected: " + expected + ", AtomicInteger actual: " + atomicCounter.get() + "  <- correct, no lock needed");

CAS itself, made visible: compareAndSet(expected, new) only succeeds if the current value still matches what you expected -- the exact primitive that makes lock-free updates safe under concurrency:

java
AtomicInteger casDemo = new AtomicInteger(10);

boolean success = casDemo.compareAndSet(10, 20);
System.out.println("CAS with a matching expected value succeeds: " + success + ", new value: " + casDemo.get());

boolean failed = casDemo.compareAndSet(10, 30);   // 10 is no longer the current value -- fails
System.out.println("CAS with a stale expected value fails: " + failed + ", value unchanged: " + casDemo.get());

Interview angle

"Implement a thread-safe counter without using synchronized" is a common exercise, and AtomicInteger is the expected answer — a good follow-up is asking how CAS actually achieves thread safety without a lock, which tests whether the candidate understands the mechanism (retry-on-conflict) rather than just knowing the class name.

In the industry

Atomic classes are the default choice for simple shared counters and flags in performance-sensitive concurrent code — metrics counters, rate limiters, simple state flags — specifically because CAS-based updates avoid the overhead of acquiring a lock under contention. For anything beyond a single field (multiple related values that need to change together atomically), a lock or a proper concurrent data structure is still the right tool; atomics don't generalize to protecting multi-field invariants.