What does LongAccumulator add over LongAdder, and when would you reach for it?
answer
- LongAccumulator = LongAdder + a custom LongBinaryOperator + identity
- Operator: associative, commutative, side-effect-free
- max/min/product/bitwise = safe; subtract/divide = unsafe
- LongAdder is the addition special case
- get() still not an atomic snapshot; getThenReset for intervals
basics
~20 sLongAccumulator is the general version of LongAdder. You give it a function (like max or multiply) and a starting value, and it combines all the values you feed in using that function across multiple cells. LongAdder is just LongAccumulator with addition.
solid answer
~50 sLongAdder is hardwired to addition. LongAccumulator generalizes it: you construct it with a LongBinaryOperator and an identity value, and accumulate() combines the running value with each new one using that operator — so you can compute a running max, min, product, or bitwise-or across many threads with the same striped, low-contention design. It uses the same internal base-plus-cells striping as LongAdder, so it scales the same way under write contention. The crucial constraint comes from the Javadoc: the order of accumulation within or across threads is not guaranteed, so for predictable results the function should be associative and commutative, and it should be side-effect-free because it may be re-applied when a contended update fails. Addition and max qualify; subtraction, division and last-value-wins do not. As with LongAdder, get() is not an atomic snapshot. Use LongAccumulator when you need a contended running reduction other than a plain sum.
code
java · 19 linesimport java.util.concurrent.atomic.LongAccumulator;
public class MaxLatency {
public static void main(String[] args) {
// Running max latency across many worker threads
LongAccumulator maxLatency =
new LongAccumulator(Long::max, Long.MIN_VALUE);
maxLatency.accumulate(42); // fold 42 into the running max
maxLatency.accumulate(17);
maxLatency.accumulate(91);
long worst = maxLatency.get(); // 91: base folded with any cells
System.out.println(worst);
// new LongAdder() is equivalent to
// new LongAccumulator((x, y) -> x + y, 0L)
}
}go deeper
Aware that LongAccumulator exists and lets you combine values with a function other than plain addition; LongAdder is the add-only version.
Can construct one with an operator and identity (e.g. Long::max, MIN_VALUE) and knows it shares LongAdder's striping and non-snapshot read.
Explains why the function should be associative, commutative and side-effect-free: accumulation order is not guaranteed and the function may be re-applied under contention. Picks safe vs unsafe operators correctly and chooses the identity properly.
Weighs LongAccumulator against alternatives (AtomicLong.accumulateAndGet at low contention, dedicated metrics histograms), reasons about floating-point associativity caveats with DoubleAccumulator, and the cost/benefit of striped reductions at scale.
## From LongAdder to LongAccumulator `LongAdder` solves one specific problem: a high-contention **sum**. `LongAccumulator` is its **generalization** — same striping machinery, but you supply the combining function instead of it being fixed to `+`. You build one with two things: ```java LongAccumulator max = new LongAccumulator(Long::max, Long.MIN_VALUE); ``` - a **`LongBinaryOperator`** — a function of two `long`s. The Javadoc says it is applied with an existing value (or the identity) as one argument and the update as the other, without promising which comes first. Here `Long::max`. - an **identity** — the starting/neutral value such that `op(identity, x) == x`. For max it's `Long.MIN_VALUE`; for sum it'd be `0`; for product `1`. `accumulate(x)` folds `x` into the running value using the operator (striped across cells just like LongAdder). `get()` reduces every cell plus the base with the operator to produce the result. `LongAdder` is literally the special case where the operator is addition and the identity is 0. ## Associative and commutative (the part interviewers probe) Values are distributed across **multiple cells in nondeterministic order**, and `get()` folds the base and the cells together. The Javadoc states the consequence: the order of accumulation within or across threads is not guaranteed, so the class is only applicable to functions for which that order does not matter, and for predictable results the function should be **associative** (`op(op(a,b),c) == op(a,op(b,c))`) **and commutative** (`op(a,b) == op(b,a)`). It should also be **side-effect-free**, because it may be re-applied when an attempted update fails under contention. Otherwise the result depends on the order updates happened to land in cells, which is not under your control. - ✅ **Safe**: addition, multiplication, `max`, `min`, bitwise `&`/`|`/`^`. These are associative and commutative; order doesn't matter. - ❌ **Unsafe**: subtraction and division, which are neither (`(a - b) - c != a - (b - c)`), and "last writer wins", `(a, b) -> b`, which is associative but not commutative, so the result depends on which cell each update landed in. Don't put side effects (logging, mutation) in the operator either — it may be called any number of times, including during retries. ## Same trade-offs as LongAdder `get()` is **not an atomic snapshot** under concurrent `accumulate()` — it's eventually-consistent, fine for monitoring/statistics. `getThenReset()` resets to the identity for interval-style reductions. Memory cost is the same striped-cell array. The fast path is lock-free CAS; it only locks briefly to allocate/resize cells. ## When to choose it Reach for `LongAccumulator` when you need a **contended running reduction that isn't a plain sum** — e.g. the maximum latency observed across all worker threads, the minimum free-buffer count, a running bitwise-OR of feature flags seen. If you only need a sum, use `LongAdder` (clearer intent, no operator to get wrong). If contention is low, a single `AtomicLong` with an `accumulateAndGet`/`updateAndGet` loop may be simpler. There are also `DoubleAdder`/`DoubleAccumulator` for floating-point, with the extra caveat that floating-point addition isn't perfectly associative, so results can differ slightly run-to-run.
- Why should the accumulator function be associative and commutative?The Javadoc says the order of accumulation within or across threads is not guaranteed: updates land in whichever cell a thread hashes to, and get() folds the base and the cells together. A function that is not associative (subtraction) or not commutative (last value wins) then gives a result that depends on that order, which you do not control.
- How would you express a max counter with LongAdder?You can't — LongAdder only does addition. Use LongAccumulator(Long::max, Long.MIN_VALUE). LongAdder is exactly LongAccumulator with the + operator and identity 0.
- Using a non-associative operator like subtraction or division
- Putting side effects in the operator (it may be invoked multiple times)
- Thinking LongAccumulator gives a precise atomic snapshot from get()
- Believing it's slower/different in scaling from LongAdder — it uses the same striping
- Forgetting to pass an identity that's neutral for the operator (e.g. 0 for max breaks negative inputs)
- LongAccumulator
- Java 1.8
- LongAdder
- Java 1.8
context
- LongAccumulator (Java SE 27 & JDK 27)docs.oracle.com
- DoubleAdder (Java SE 27 & JDK 27)docs.oracle.com