CKTIS / Java
LongAdder: updating, reading, and resetting
Use `LongAdder` to collect statistics updated by multiple threads. Learn which methods change the total, when a read is exact, and why `sumThenReset()` does not create an atomic boundary between reporting intervals.
Version: Java SE 21
Syntax
import java.util.concurrent.atomic.LongAdder;
// LongAdder instance methods in Java SE 21:
public void increment()
public void add(long x)
public long sum()
public long sumThenReset()
public void reset()java.util.concurrent.atomic.LongAdder maintains a long total that starts at zero. Under heavy contention, it can spread updates across multiple internal variables. This makes it useful for collecting statistics, not for coordinating threads.
increment() adds 1, just like add(1L). add(long x) adds the supplied value, which can be negative. Both methods return void. sum() returns the total as a long without changing it. The result is accurate when no updates run concurrently. Otherwise, the read is not an atomic snapshot and may omit some concurrent updates.
reset() zeroes the same instance and returns nothing. Use it only when you know no thread will update the counter during the call. Without concurrent updates, sumThenReset() has the effect of reading with sum() and then calling reset(): it returns the previous total as a long and clears the counter. It is not an atomic boundary between reporting intervals. If updates overlap the call, the returned total is not guaranteed to be the final total before the reset.
Examples
import java.util.concurrent.atomic.LongAdder;
public class Main {
public static void main(String[] args) {
LongAdder requests = new LongAdder();
LongAdder bytes = new LongAdder();
for (long size : new long[] {512L, 1024L, 2048L, 3072L, 376L}) {
requests.increment();
bytes.add(size);
}
System.out.println("Requests: " + requests.sum());
System.out.println("Bytes: " + bytes.sum());
System.out.println("Bytes returned by sumThenReset(): " + bytes.sumThenReset());
System.out.println("Bytes after sumThenReset(): " + bytes.sum());
requests.reset();
System.out.println("Requests after reset(): " + requests.sum());
}
}Result
Requests: 5 Bytes: 7032 Bytes returned by sumThenReset(): 7032 Bytes after sumThenReset(): 0 Requests after reset(): 0
One thread counts five requests and a total of 7032 bytes. `sumThenReset()` returns 7032 and clears the byte counter; `reset()` clears the request counter without returning its previous value.
Related lessons
- Java · Lesson 31 · Advanced · Version: 2