Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

How does LongAdder differ from AtomicLong, and when should you use each?

AtomicLong keeps one value that every thread updates, while LongAdder keeps a base value plus an array of cells, so that threads that collide are spread over different cells and stop contending. Because of that, LongAdder's sum() adds the base and all cells and is not an atomic snapshot while updates continue. We use LongAdder for frequently updated statistics such as metrics counters, and AtomicLong when we need compareAndSet, an exact current value or a sequence of unique values; LongAdder also uses more memory once contention creates its cells.

Why this question is asked

Both classes count, and both are thread-safe, so the choice looks like a matter of taste. It is not: they are built for different jobs, and picking the wrong one either wastes CPU on a hot counter or produces subtly wrong numbers where exactness matters. Interviewers ask this to see whether we understand the internals well enough to explain the trade-off rather than just repeat 'LongAdder is faster'. In this answer, we will recap how AtomicLong behaves under contention, look inside LongAdder step by step, see exactly what sum() does and does not promise, and then go through when to use each.

1A Quick Recap of AtomicLong Under Contention

An AtomicLong holds one long in one place in memory. incrementAndGet changes it with an atomic instruction, lock xadd on x86, and returns the new value. That return value is precise: it is exactly the count after our increment, and no other thread got the same number.

The cost is that all threads write the same memory location. A CPU core must own the cache line holding a variable exclusively to write it, so with many cores incrementing, the line travels from core to core and the increments line up one after another. With two threads this hardly matters; with thirty-two threads hammering one counter, most of each increment's time is spent waiting for the line to arrive.

2How LongAdder Spreads the Work

LongAdder, in java.util.concurrent.atomic, starts with just a base field. While there is no contention, increment() does a CAS on the base, much like an AtomicLong. The first time a CAS on the base fails, which means two threads collided, LongAdder creates an array of cells, small objects that each hold a long. From then on, each thread picks a cell using a per-thread hash value, called a probe, and does its CAS there.

If a thread's CAS on its cell also fails, LongAdder changes that thread's probe so it moves to another cell, and when collisions keep happening it doubles the array, up to roughly the number of CPUs. Each cell is padded with @Contended so that two cells never share a cache line, which would bring back the contention. After a short while, each busy thread effectively has a cell of its own, and increments no longer fight over memory.

Java
LongAdder requests = new LongAdder();
requests.increment(); // no contention yet: CAS on base
// 32 threads now increment at the same time:
// collisions on base -> cells array created (2, then 4, ... up to about the CPU count)
// each thread CASes its own padded cell, rarely colliding
requests.add(5); // same path, adds 5 to this thread's cell
long total = requests.sum(); // base + cell[0] + cell[1] + ...
Step throughInside a contended LongAdder
  1. baseupdated first; used while there is no contention
  2. cells[0] .. cells[n-1]created on first collision; n grows by doubling up to about the CPU count
  3. Per-thread probepicks a cell; rehashed when that cell is contended
  4. sum()reads base and every cell and adds them up

4 layers, from the top down. Step through them one at a time.

3What sum() Promises and What It Does Not

sum() walks the base and the cells and adds them. It takes no lock and does not stop other threads, so if increments happen while it walks, some are included and some are not, depending on whether they hit a cell before or after sum() read it. The result is close to the true total, but it is not a snapshot of one instant, and it may not equal any value the counter actually held at a single moment.

For a request counter read by a metrics scraper every 15 seconds, that is perfectly fine: an increment missed now appears in the next reading. It is not fine when we need an exact decision, such as 'allow the request only if fewer than 100 are in progress'. LongAdder has no incrementAndGet and no compareAndSet, precisely because it never has one place holding the current total. sumThenReset() exists for periodic collection, but it has the same non-atomic caveat.

4When to Use Each

The rule of thumb follows from the design. If many threads update a number frequently and readers only need an approximate total occasionally, LongAdder wins: request counts, bytes sent, cache hits and misses, errors per type. These are the statistics that metrics libraries record on hot paths.

If a thread needs to know the value as a result of its own update, AtomicLong is the tool: generating sequence numbers, making a decision on the new value, implementing a limit with compareAndSet, or any logic that reads the current value and acts on it. And when contention is low, AtomicLong is simply smaller and slightly faster, so there is no reason to switch.

AtomicLong or LongAdder
QuestionAtomicLongLongAdder
Many threads update oftenContends on one cache lineScales across cells
Need the value after my updateincrementAndGet returns itNot available
Need compareAndSetYesNo
Read an exact totalget() is exactsum() is not a snapshot
MemoryOne longBase plus padded cells, over 100 bytes each
Typical useSequences, limits, stateMetrics and statistics

5The Memory Cost

An AtomicLong is a small object with one long field. An uncontended LongAdder is not much bigger, but once contention appears it allocates its cell array, and each cell is padded to keep it on its own cache line, so each one occupies well over a hundred bytes, often a few hundred depending on the JVM's padding setting (a tool such as JOL shows the exact layout). On a 32-core machine that can be several kilobytes for one counter. That is trivial for a few hundred counters, but a design that creates a LongAdder per user or per tag value can end up with millions of them. The cells are never shrunk, so a counter that was contended once keeps its memory.

6Follow-up questions

Is LongAccumulator the same idea?

Yes. LongAccumulator uses the same cells but applies any associative, commutative function, such as Math::max, instead of addition. It is the right tool for a high-rate maximum or minimum, with the same caveat that reading it during updates is not a snapshot.

Why not always use LongAdder for counters?

Because many counters are not hot, and some need exact values. An uncontended AtomicLong is simpler, smaller and gives precise reads and compareAndSet, so LongAdder is worth it only where profiling or the expected rate shows contention.

Can sum() ever go backwards?

With only increments, two consecutive calls to sum() from one thread should not decrease. With add of negative values, or with sumThenReset running concurrently, readings can move in ways that surprise us, which is another reason to keep LongAdder for simple statistics.

7Conclusion

In this answer, we saw that AtomicLong keeps one value that all threads contend on, while LongAdder starts with a base and creates padded cells on contention so threads update different memory. Its sum() adds base and cells without a lock and is not an atomic snapshot, which is fine for metrics but not for decisions. So LongAdder fits high-rate statistics, AtomicLong fits sequences, compareAndSet and exact reads, and LongAdder's cells cost noticeably more memory under contention.

What to say in the interviewAbout 90 seconds aloud

Open with

AtomicLong is one value that every thread updates with an atomic instruction, so its incrementAndGet gives me an exact result, but under heavy contention all cores fight over the same cache line.

Then, if they want more

LongAdder is built for that case. It starts with a base field, and the first time two threads collide on it, it creates an array of cells, each padded to its own cache line.

Each thread then picks a cell with a per-thread hash, moves to another cell if it collides again, and the array can grow up to about the number of CPUs, so busy threads end up updating separate memory.

The total comes from sum, which adds the base and all the cells without locking, so while updates are happening it's not an atomic snapshot; it's a value close to the truth that might miss in-flight increments. That's why I use LongAdder for frequently updated statistics, like request counts or bytes sent, where a scraper reads it every few seconds.

I use AtomicLong when I need compareAndSet, the exact value after my own update, or unique sequence numbers, and also whenever contention is low, because it's smaller and simpler. The other cost of LongAdder is memory: once contended, each cell takes over a hundred bytes with padding, so creating one per user or per tag combination can get expensive.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does LongAdder differ from AtomicLong, and when should you use each?": https://scrivio-interview-library.netlify.app/java/atomics/3c00fac714/