Video in progress

Strong Middle 🧵 Concurrency

When very many threads increment one counter, why is LongAdder faster than AtomicLong?

In AtomicLong, all threads fight with CAS over a single memory cell and retry a lot. LongAdder spreads the sum over several cells when contention appears, and sum() adds them up. Writes are fast, but a read is not an exact "instantaneous" value.

📖 Answer

Under high contention, the problem with AtomicLong.incrementAndGet() is CAS failures. If 32 threads try at once, one wins and 31 retry. On top of that, the cache line keeps bouncing between cores.

LongAdder initially uses a single base field. When CAS starts failing, a Cell[] array is created and each thread (by hash) increments its own cell. The cells sit on separate cache lines thanks to @Contended, so there is no false sharing.

private final LongAdder requests = new LongAdder();

void onRequest() { requests.increment(); }

long total() { return requests.sum(); }

When to use LongAdder:

  • metrics, statistics, counters: written a lot, read rarely.

When to use AtomicLong:

  • when the value itself is needed for a decision: ID generation (incrementAndGet returns a unique number), compareAndSet logic, checking a limit;
  • when contention is low, you won't notice a difference, and LongAdder uses more memory.

If sum() is called while other threads are writing, the result may not match the value at any single moment. A pattern you often see is "ConcurrentHashMap<String, LongAdder>" + computeIfAbsent(k, x -> new LongAdder()).increment(), the classic counter from the pre-Micrometer era.