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.
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:
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());