ProLesson 9.10Advanced3 min readUpdated 30 October 2026
Atomic variables and CAS
Lock-free thread safety with AtomicInteger and friends, how compare-and-set works, and when LongAdder beats AtomicLong.
For a single shared counter or reference, a lock is heavyweight. The java.util.concurrent.atomic classes make single-variable updates thread-safe without locks, using a CPU instruction called compare-and-set (CAS).
01AtomicInteger fixes the counter
AtomicCounter.java
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
public static void main(String[] args) throws InterruptedException {
AtomicInteger count = new AtomicInteger();
Runnable addMany = () -> {
for (int i = 0; i < 100_000; i++) count.incrementAndGet(); // atomic count++
};
Thread a = new Thread(addMany), b = new Thread(addMany);
a.start(); b.start(); a.join(); b.join();
System.out.println("Count: " + count.get());
}
}Count: 200000
Loading the rest of the lesson…