LongAdder Contended Counter Increments
Maintain a hot counter across threads with LongAdder, which splits contention across cells and exposes sum() once aggregation finishes.
Code
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
public class HitCounter {
public static void main(String[] args) throws InterruptedException {
LongAdder hits = new LongAdder();
int threads = 4;
int perThread = 25_000;
ExecutorService pool = Executors.newFixedThreadPool(threads);
CountDownLatch done = new CountDownLatch(threads);
for (int t = 0; t < threads; t++) {
pool.submit(() -> {
for (int i = 0; i < perThread; i++) {
hits.increment(); // 各线程写各自的 cell,不竞争同一个 CAS 变量
}
done.countDown();
});
}
done.await();
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("expected = " + (threads * perThread));
System.out.println("sum = " + hits.sum()); // 收尾一次性汇总
hits.add(50); // 批量累加同样支持
System.out.println("after sumThenReset = " + hits.sumThenReset());
}
}How it works
Count the class HitCounter as the entire surface area of LongAdder Contended Counter Increments.
The file repeats itself only inside for (int t = 0; t < threads; t++).
Using it
Running the file prints labeled results such as expected =, sum =, after sumThenReset = — each operation’s effect is visible in the output.
Key statements
ExecutorService pool = Executors.newFixedThreadPool(threads);
for (int i = 0; i < perThread; i++) {
hits.increment(); // 各线程写各自的 cell,不竞争同一个 CAS 变量
}
int perThread = 25_000;
Interactive Tools for This Topic
FAQ
- What does LongAdder Contended Counter Increments print when run?
- Execute the whole file; each printed line is prefixed with a label like `expected =`, `sum =`, `after sumThenReset =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.