Java / Java 21 Interview Questions
What are the java.util.concurrent.atomic classes and how do they work?
The java.util.concurrent.atomic package provides lock-free, thread-safe single-variable operations using CPU-level Compare-And-Swap (CAS) instructions. They are faster than synchronized blocks for single-variable updates because they avoid locking entirely.
// AtomicInteger — counter safe for use from multiple threads
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // returns new value: 1
counter.getAndIncrement(); // returns old value: 1, new value: 2
counter.addAndGet(5); // atomically add 5
counter.compareAndSet(7, 0); // only updates if current == 7
// AtomicLong, AtomicBoolean, AtomicReference work the same way
// AtomicReference — CAS on an object reference
AtomicReference name = new AtomicReference<>("initial");
boolean updated = name.compareAndSet("initial", "updated"); // true
// LongAdder — better than AtomicLong under HIGH contention
LongAdder hitCount = new LongAdder();
hitCount.increment(); // thread-safe, very fast under contention
long total = hitCount.sum(); // reads the aggregate
// LongAdder splits the counter across multiple cells to reduce contention
// AtomicIntegerArray, AtomicLongArray, AtomicReferenceArray
AtomicIntegerArray arr = new AtomicIntegerArray(10);
arr.compareAndSet(5, 0, 99); // CAS on index 5
// VarHandle (Java 9) — generalized CAS on any field
// More powerful but more verbose than atomic classes LongAdder vs AtomicLong: at low contention they perform similarly. Under high contention (many threads incrementing simultaneously), LongAdder is significantly faster because it distributes the counter across multiple cells and only aggregates in sum(). Use LongAdder for pure counters; use AtomicLong when you need atomic read-modify-write with a precise current value (e.g., compareAndSet patterns).
More Related questions...