Java

AtomicInteger / LongAdder

admin by @admin ADMIN
8m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Lock-free atomics for shared counters. `AtomicInteger` for low contention; `LongAdder` for high contention (shards internally — much faster under heavy parallel load).
Java
Raw
import java.util.concurrent.atomic.*;
import java.util.concurrent.*;

class Demo {
    // Low contention: AtomicLong is great
    static final AtomicLong requestId = new AtomicLong();

    long nextRequestId() { return requestId.incrementAndGet(); }

    // High contention: LongAdder is faster (sharded internally)
    static final LongAdder pageViews = new LongAdder();

    void recordPageView() { pageViews.increment(); }
    long totalPageViews() { return pageViews.sum(); }

    void example() throws Exception {
        var pool = Executors.newFixedThreadPool(16);
        for (int i = 0; i < 16; i++) {
            pool.submit(() -> {
                for (int j = 0; j < 1_000_000; j++) recordPageView();
            });
        }
        pool.shutdown();
        pool.awaitTermination(1, TimeUnit.MINUTES);
        System.out.println(totalPageViews());   // 16_000_000

        // Compare-and-swap for flag patterns
        var fired = new AtomicBoolean(false);
        if (fired.compareAndSet(false, true)) {
            System.out.println("first to fire");
        }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.