LongAccumulator and DoubleAccumulator¶
LongAccumulator and DoubleAccumulator are classes in Java introduced in version 8 within the java.lang package. They belong to the Striped64 family of concurrent utilities, which are designed to support accumulators in concurrent environments using a lock-free approach that remains thread-safe.^[600-developer__java__java-base__java-Runtime-Number.md]
Core Concept¶
These classes provide a mechanism for maintaining running totals (accumulation) across multiple threads efficiently. The Striped64 component underlying them allows for high-performance updates by reducing contention compared to standard atomic variables.^[600-developer__java__java-base__java-Runtime-Number.md]
Specialized Variants¶
The java.util.concurrent package provides specialized, simpler versions of these accumulators for common addition operations:
* LongAdder: One or more variables that together maintain an initially zero sum.
* DoubleAdder: One or more variables that together maintain an initially zero double sum.^[600-developer__java__java-base__java-Runtime-Number.md]
When instantiated with default parameters, these specialized classes function identically to their generic counterparts. Specifically, new [LongAdder](<./longadder.md>)() is equivalent to new [LongAccumulator](<./longaccumulator.md>)((x, y) -> x + y, 0L), and new DoubleAdder() is equivalent to new DoubleAccumulator((x, y) -> x + y, 0.0).^[600-developer__java__java-base__java-Runtime-Number.md]
Usage Example¶
The following example demonstrates the use of LongAccumulator with a thread pool to perform concurrent accumulation.^[600-developer__java__java-base__java-Runtime-Number.md]
[LongAccumulator](<./longaccumulator.md>) accumulator = new [LongAccumulator](<./longaccumulator.md>)(Long::sum, 0L);
int numberOfThreads = 4;
int numberOfIncrements = 100;
Runnable accumulateAction = () -> IntStream
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);
}
Related Concepts¶
- [[AtomicInteger]]
- [[Java Concurrency]]
- Striped64
Sources¶
^[600-developer__java__java-base__java-Runtime-Number.md]