CKTIS / Java
LongAdder — concurrent counting and summation
LongAdder maintains a long sum updated by multiple threads. It suits statistics, but sum() does not provide an atomic snapshot, and resetting requires control over concurrent updates.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
LongAdder counter = new LongAdder();
counter.increment(); // void
counter.add(longValue); // void
long total = counter.sum();
long previous = counter.sumThenReset();
counter.reset(); // voidjava.util.concurrent.atomic.LongAdder starts at zero and spreads updates across internal variables to reduce thread contention. Under high contention it can offer higher throughput than AtomicLong, at the cost of memory. Use it for statistics, not fine-grained synchronization control.
LongAdder.increment() adds one, and LongAdder.add(long) adds the supplied value; both return void. LongAdder.sum() returns a long, but is not an atomic snapshot: it may omit updates occurring during the read. Without concurrent updates, the result is accurate.
LongAdder.reset() clears the state and returns void; use it only when no thread is updating the counter. LongAdder.sumThenReset() returns the sum and clears the state. Do not treat it as an atomic measurement-period boundary: with concurrent updates, its result need not be the final value before resetting.
In the example, both join() calls precede reads and resets. This makes the expected output deterministic. The documentation scope is Java SE 21; the repository runtime does not attest the production runtime.
Examples
import java.util.concurrent.atomic.LongAdder;
public class Main {
public static void main(String[] args) throws InterruptedException {
LongAdder counter = new LongAdder();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread first = new Thread(task);
Thread second = new Thread(task);
first.start();
second.start();
first.join();
second.join();
counter.add(5);
System.out.println(counter.sum());
System.out.println(counter.sumThenReset());
System.out.println(counter.sum());
counter.add(7);
counter.reset();
System.out.println(counter.sum());
}
}Result
2005 2005 0 0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.