skip to content

What is LongAdder, and why might you prefer it over AtomicLong for a heavily-incremented counter?

level: middleimportance: should knowfreq 55%

answer

  1. AtomicLong = one hot location every write needs
  2. LongAdder = stripe writes across padded cells
  3. sum() = base + all cells, NOT an atomic snapshot
  4. Write-heavy / read-rare → LongAdder
  5. Need compareAndSet or frequent exact reads → AtomicLong

basics

~20 s

LongAdder is a counter for many threads. Instead of one shared number, it keeps several internal cells so threads update different ones and rarely collide. You read the total with sum(). Under heavy concurrent writes it's faster than AtomicLong.

solid answer

~50 s

AtomicLong keeps a single value that every thread updates atomically in the same memory location. Under high write contention every update needs that one cache line exclusively, so the threads serialize on it, and compare-and-swap (CAS) retry loops such as updateAndGet also fail and retry. LongAdder instead spreads writes across an internal array of cells: different threads hash to different cells, so their CAS operations hit different memory and rarely conflict. add() CASes a base field until contention appears, then the thread's cell; sum() adds the base and all cells. The trade-off: sum() is not a precise instantaneous snapshot if updates run concurrently, and LongAdder uses more memory than a single long. So prefer LongAdder for write-heavy, read-rarely counters (metrics, statistics); prefer AtomicLong when you need a single atomic value you frequently read or compare-and-set, or when contention is low.

code

java · 19 lines
java
import java.util.concurrent.atomic.LongAdder;

public class RequestCounter {
    public static void main(String[] args) {
        LongAdder requests = new LongAdder();

        // Hot path: many threads, fire-and-forget
        requests.increment();        // add(1) -> base or a cell, lock-free CAS
        requests.add(5);

        // Cold path: read occasionally
        long total = requests.sum(); // base + all cells; NOT an atomic snapshot

        // Interval metric: read and zero each cell (not atomic as a whole)
        long sinceLast = requests.sumThenReset();

        System.out.println(total + " " + sinceLast + " " + requests.sum());
    }
}

go deeper

for a junior

Knows LongAdder is a thread-safe counter and that it's a good choice when many threads increment a counter; reads the total with sum().

for a middle

Explains the single-hot-location problem of AtomicLong under contention and that LongAdder stripes writes across cells; knows sum() is not a perfect snapshot.

for a senior

Articulates the CAS contention / cache-line bouncing mechanism, the base+cells structure, the read-vs-write and memory trade-offs, and gives concrete decision criteria (metrics vs sequence generator).

for a principal

Reasons about when striping helps vs hurts at the system level (false sharing, @Contended padding, NUMA, memory footprint per counter at scale), and whether a metrics library already abstracts this; weighs LongAdder against AtomicLong, sharded counters, or thread-local aggregation.

## The problem LongAdder solves A **counter** is a number many threads increment. The naive `count++` is three steps (read, add one, write), so two threads can interleave and lose an update — a *race condition*. The classic fix is `AtomicLong`. **`AtomicLong`** holds one `long` and updates it with **compare-and-swap (CAS)**: a hardware instruction that says "if this memory still holds the value I read, replace it with my new value; otherwise tell me you failed." In the JDK source, `incrementAndGet()` ends in a loop inside `Unsafe.getAndAddLong`: read current value `v`, compute `v+1`, CAS from `v` to `v+1`; if CAS fails (another thread changed it first), reread and retry. HotSpot's JIT replaces that loop with a single atomic get-and-add where the platform supports one, while `compareAndSet`-based methods such as `updateAndGet` keep the retry loop. Either way the update is atomic **without locks**: no thread is ever blocked on a lock. **Contention** is the issue. When dozens of threads all hammer the *same* `AtomicLong`, every update needs the *same* cache line held exclusively by its core. The line ping-pongs between CPU cores (**cache-line bouncing**, a case of *true sharing*: every thread really does need that one value), and in a CAS loop the losers also fail and retry. Effectively the threads serialize on one location. ## How LongAdder works `LongAdder` (Java 8+, in `java.util.concurrent.atomic`) trades a single hot location for **many cool ones**. Internally it has: - a `base` field (a `volatile long` updated by CAS while there is no contention), and - a lazily-grown array of **`Cell`** objects, each holding its own `long`. While no cell table exists, `add(x)` CASes `base`, and if that succeeds it is done. The first failed CAS on `base` creates a two-slot table, whose slots stay empty until a thread needs one, and from then on `add(x)` goes straight to a `Cell` chosen by a per-thread hash code that `ThreadLocalRandom` maintains, and CASes *that* cell; `base` is only a fallback while the table is being set up. Because different threads mostly hash to different cells, their CAS operations touch **different memory addresses on different cache lines**, so they rarely collide. On repeated collisions the table doubles, up to the nearest power of two at or above the CPU count, and the `Cell`s are padded (`@Contended`) so no two share a cache line. `increment()` is just `add(1)`. To get the total, **`sum()`** returns `base` plus every cell's value. This is the key trade-off: `sum()` is **not atomic** with respect to concurrent `add`s. It reads the cells one by one, so if updates are happening during the traversal, the result reflects some in-between moment — it's eventually-consistent, not a precise instantaneous snapshot. `sumThenReset()` exists for interval metrics. ## When to use which - **Prefer `LongAdder`** for **write-heavy, read-rare** counters under contention: request counts, hit/miss tallies, throughput metrics — anywhere you fire-and-forget `increment()` from many threads and only occasionally read the total. - **Prefer `AtomicLong`** when you (a) need a single value you read frequently or must read atomically, (b) need `compareAndSet`/`getAndSet` to drive logic (e.g. a sequence generator, a one-shot flag, an ID allocator), or (c) have low contention where the extra memory and indirection of LongAdder aren't justified. ## Cost trade-offs LongAdder uses more memory (an array of padded cells, sized near CPU count) and gives up a cheap exact read. In exchange, under high contention its expected throughput is, in the Javadoc's words, significantly higher than AtomicLong's; under low contention the two classes have similar characteristics. The whole idea is *striping* the contended state.

  • Is LongAdder.sum() exact?
    Not under concurrent updates. It sums the base and each cell sequentially, so a concurrent add can land before or after a given cell is read. The result is correct only if it converges in a quiescent moment. For an exact running value you read constantly, AtomicLong is the better fit.
  • Does LongAdder use locks?
    Not on the hot path: adds CAS the base or a cell. A spinlock flag acquired by CAS, cellsBusy, guards creating and resizing the cell table and attaching a new Cell to an empty slot. A thread that finds it taken does not block; it tries another slot or the base.

  • Claiming sum() returns a precise atomic snapshot during concurrent updates
  • Saying LongAdder is always faster than AtomicLong — at low contention AtomicLong can be as fast and uses less memory
  • Thinking LongAdder supports compareAndSet (it doesn't — no atomic value semantics, only add/sum/reset)
  • Confusing it with a lock-based counter; the fast path is lock-free CAS
  • Assuming LongAdder gives a single canonical value you can CAS on

LongAdder
Java 1.8

context