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.
Code
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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Word Frequency CounterCount word occurrences in text with Unicode-aware tokenization, optional lowercasing, and a ranked frequency table.
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=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.