Multithreading: accumulateAndGet folds a value with a function

accumulateAndGet applies a custom two-argument function to combine the current value with a new one, atomically, without a separate read-modify-write. Here it is used to track a running maximum across several updates.

Code
AtomicInteger max = new AtomicInteger(Integer.MIN_VALUE);
int[] values = { 5, 12, 3, 47, 8 };
for (int v : values) {
    max.accumulateAndGet(v, Math::max);
}
System.out.println("Maximum seen: " + max.get());
Output
Maximum seen: 47
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms