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");
}
}
}
Create a free account and build your private vault. Share publicly whenever you want.