Atomic Variables CAS Counter

Track concurrent metrics with AtomicLong and LongAdder, and drive a compare-and-set loop when the update depends on the previous value.

JavaResilience

Code

snippet
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class AtomicMetrics {

    public static void main(String[] args) throws InterruptedException {
        AtomicLong bytesIn = new AtomicLong();
        LongAdder requestCount = new LongAdder();

        Thread[] workers = new Thread[4];
        for (int w = 0; w < workers.length; w++) {
            workers[w] = Thread.ofPlatform().start(() -> {
                for (int i = 0; i < 10_000; i++) {
                    bytesIn.addAndGet(512);
                    requestCount.increment();
                }
            });
        }
        for (Thread worker : workers) {
            worker.join();
        }
        System.out.println("bytes=" + bytesIn.get() + " requests=" + requestCount.sum());

        // CAS 循环:更新依赖旧值时,失败即重读重试
        AtomicLong highWater = new AtomicLong();
        long candidate = 9_999;
        while (true) {
            long known = highWater.get();
            if (candidate <= known || highWater.compareAndSet(known, candidate)) {
                break;
            }
        }
        System.out.println("highWater=" + highWater.get());
    }
}

What the code does

Atomic Variables CAS Counter keeps everything in the class AtomicMetrics.

Iteration happens inside for (int w = 0; w < workers.length; w++) — everything outside it runs once.

Applying it

The demo output is labeled (bytes=, highWater=), so the printed lines read as a trace of the operations that ran.

Statements that matter

workers[w] = Thread.ofPlatform().start(() -> {
for (int i = 0; i < 10_000; i++) {
bytesIn.addAndGet(512);
requestCount.increment();
}
});
Thread[] workers = new Thread[4];
for (Thread worker : workers) {
worker.join();
}

Interactive Tools for This Topic

FAQ

What does Atomic Variables CAS Counter print when run?
Run it as a complete program — the output lines carry labels such as `bytes=`, `highWater=`.