CKTIS / Java
LongAdder: increment, add, and read the sum
Use `increment()` to count one, `add(long)` to apply a delta, and `sum()` to read the total. Learn how to merge partial totals and when the read gives an exact result.
Version: Java SE 21
Syntax
Java SE 21 — java.util.concurrent.atomic.LongAdder
public LongAdder()
public void increment()
public void add(long x)
public long sum()
LongStream.collect: (left, right) -> left.add(right.sum())In Java SE 21, LongAdder.increment/add/sum are the update and read operations of java.util.concurrent.atomic.LongAdder, a long total that multiple threads can update. new LongAdder() starts at zero. increment() adds one, just like add(1L). add(long x) adds x, which may be negative. Both updates return void. sum() returns a long without resetting the adder.
In a parallel LongStream.collect(...), LongAdder::new creates fresh partial containers. The accumulator processes each element, and the combiner (left, right) -> left.add(right.sum()) reads the right subtotal and adds it to the left container without changing the right. This collect overload keeps partial containers isolated during accumulation, so parallel execution does not itself require LongAdder.
A call to sum() during updates is not an atomic snapshot: it may omit updates that occur while the total is being read. For an exact final result, read the returned container after collect completes, as in the example. If you manage the threads yourself, use Thread.join() to wait for every updating thread to finish and ensure no other thread is still updating the adder.
Examples
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.LongStream;
public class LongAdderDemo {
public static void main(String[] args) {
LongAdder total = LongStream.of(1, 4, 1, -2, 3)
.parallel()
.collect(LongAdder::new,
(partial, delta) -> {
if (delta == 1L) {
partial.increment();
} else {
partial.add(delta);
}
},
(left, right) -> left.add(right.sum()));
System.out.println(total.sum());
}
}Result
7
The program is expected to print `7` because `1 + 4 + 1 - 2 + 3 = 7`. The result does not depend on how the stream is partitioned, and the final read happens after `collect` returns.
Related lessons
- Java · Lesson 24 · Advanced · Version: 2