Chapter 1: Protect Your Shared Mutable State ← Avoid Locks

Avoid Active Waiting


/** thread safe */
class Counter {

  private final AtomicLong count = new AtomicLong();

  void increment(long amount) {
    if (amount < 1) {
      throw new IllegalArgumentException("Only increments!");
    }

    this.count.addAndGet(amount);
  }
}

The AtomicLong is lock-free, but all threads still update one and the same memory location. When many threads increment at the same time, they keep competing for it: compare-and-set attempts fail and have to be retried, and the CPU cores keep passing the same cache line back and forth. The threads are busy, but much of that work is waiting in disguise.


/** thread safe */
class Counter {

  private final LongAdder count = new LongAdder();

  void increment(long amount) {
    if (amount < 1) {
      throw new IllegalArgumentException("Only increments!");
    }

    this.count.add(amount);
  }
}

A LongAdder spreads the updates over several internal cells. Under contention, different threads add to different cells, so they rarely get in each other's way. Reading the value with sum() adds up all cells.

This scales much better when many threads count at the same time, at the cost of more memory. And sum() is not an atomic snapshot: while other threads keep adding, the result may miss the very latest increments. That's perfectly fine for counters and statistics, which are written often and read rarely. When you need exact values for decisions, such as generating unique IDs, stick with AtomicLong.