Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

LongAccumulator — concurrent aggregation of long values

LongAccumulator combines long values using a supplied function. It supports concurrent updates, but get() does not provide an atomic snapshot while updates are occurring.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

LongAccumulator(LongBinaryOperator accumulatorFunction, long identity)
void accumulate(long x)
long get()

LongAccumulator, in java.util.concurrent.atomic, supports concurrent aggregation of long values, such as statistics, rather than synchronization control. Internally, it can spread updates across multiple variables, reducing contention at the cost of memory.

The constructor takes a LongBinaryOperator function and its identity element. The function should be associative, commutative, and side-effect-free: ordering is not guaranteed, and evaluation may be repeated. For Long::max, the identity is Long.MIN_VALUE.

LongAccumulator.accumulate(long x) incorporates its argument into the aggregation and returns void. LongAccumulator.get() returns the long result but is not an atomic snapshot: it may omit concurrent updates. Without concurrent updates, the result is accurate.

Examples

import java.util.concurrent.atomic.LongAccumulator;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        LongAccumulator maximum =
                new LongAccumulator(Long::max, Long.MIN_VALUE);

        Thread first = new Thread(() -> {
            maximum.accumulate(-8L);
            maximum.accumulate(12L);
        });
        Thread second = new Thread(() -> {
            maximum.accumulate(7L);
            maximum.accumulate(-3L);
        });

        first.start();
        second.start();
        first.join();
        second.join();

        System.out.println(maximum.get());
    }
}

Result

12

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources