LongAccumulator¶
LongAccumulator is a class introduced in Java 8 within the java.lang package, designed as a concurrent component for maintaining a running sum updated by multiple threads efficiently.^[600-developer-java-java-base-java-runtime-number.md]
Functional Characteristics¶
LongAccumulator is part of the Striped64 family of constructs, which are lock-free yet remain thread-safe.^[600-developer-java-java-base-java-runtime-number.md] This mechanism allows it to operate as a high-performance accumulator in concurrent environments.
One of the key features of LongAccumulator is its flexibility. It allows the programmer to supply a custom function to determine how values are combined, rather than being restricted to simple addition.^[600-developer-java-java-base-java-runtime-number.md]
Relationship with LongAdder¶
The LongAccumulator class serves as a more generalized version of the LongAdder class^[600-developer-java-java-base-java-runtime-number.md].
Specifically, the statement new [LongAdder](<./longadder.md>)() is functionally equivalent to new LongAccumulator((x, y) -> x + y, 0L).^[600-developer-java-java-base-java-runtime-number.md] This means LongAdder is essentially a specialized LongAccumulator hard-coded to perform addition starting from zero.
Usage Example¶
Instantiating a LongAccumulator requires two arguments: an accumulation function and an initial value.^[600-developer-java-java-base-java-runtime-number.md]
The following example demonstrates how to create an accumulator that sums long values:^[600-developer-java-java-base-java-runtime-number.md]
LongAccumulator accumulator = new LongAccumulator(Long::sum, 0L);
To update the value in a concurrent context, threads invoke the accumulate method:^[600-developer-java-java-base-java-runtime-number.md]
Runnable accumulateAction = () -> IntStream
.rangeClosed(0, numberOfIncrements)
.forEach(accumulator::accumulate);
Related Concepts¶
Sources¶
^[600-developer-java-java-base-java-runtime-number.md]