LongAccumulator For Concurrent Max

Aggregate a concurrent maximum with LongAccumulator while a LongAdder collects totals, then reset both without locking.

JavaResilience

Code

snippet
import java.util.Random;
import java.util.concurrent.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;

public class LongAccumulatorDemo {
    public static void main(String[] args) throws Exception {
        // 单位元 0 + max 函数:无锁并发求最大值
        LongAccumulator max = new LongAccumulator(Long::max, 0L);
        LongAdder total = new LongAdder();

        Thread[] workers = new Thread[4];
        for (int t = 0; t < workers.length; t++) {
            final int id = t;
            workers[t] = new Thread(() -> {
                Random random = new Random(100 + id);
                for (int i = 0; i < 1_000; i++) {
                    long sample = 1 + random.nextInt(9_999);
                    max.accumulate(sample);
                    total.add(sample);
                }
            });
            workers[t].start();
        }
        for (Thread worker : workers) {
            worker.join();
        }

        System.out.println("max sample: " + max.get());
        System.out.println("sum: " + total.sum());

        // reset 回到单位元,供下一轮统计复用
        max.reset();
        total.reset();
        System.out.println("after reset: max=" + max.get() + " sum=" + total.sum());
    }
}

Inside the snippet

LongAccumulator For Concurrent Max comes down to the class LongAccumulatorDemo.

Iteration happens inside for (int t = 0; t < workers.length; t++) — everything outside it runs once.

Using it

The demo output is labeled (max sample:, sum:, after reset: max=), so every printed line maps back to its originating operation.

Key statements

Thread[] workers = new Thread[4];
workers[t] = new Thread(() -> {
    Random random = new Random(100 + id);
    for (int i = 0; i < 1_000; i++) {
        long sample = 1 + random.nextInt(9_999);
        max.accumulate(sample);
        total.add(sample);
    }
});
for (Thread worker : workers) {
    worker.join();
}

Interactive Tools for This Topic

FAQ

What does LongAccumulator For Concurrent Max print when run?
Run it as a complete program — the output lines carry labels such as `max sample:`, `sum:`, `after reset: max=`.