java 39 lines · 6 steps

A thread-safe request counter with AtomicInteger

An AtomicInteger backs a lock-free counter that caps concurrent requests using compare-and-set.

Explained by highlit
1import java.util.concurrent.atomic.AtomicInteger;
2 
3public final class RequestCounter {
4 
5 private final AtomicInteger count = new AtomicInteger();
6 private final int limit;
7 
8 public RequestCounter(int limit) {
9 this.limit = limit;
10 }
11 
12 public int increment() {
13 return count.incrementAndGet();
14 }
15 
16 public int decrement() {
17 return count.updateAndGet(current -> current > 0 ? current - 1 : 0);
18 }
19 
20 public boolean tryAcquire() {
21 while (true) {
22 int current = count.get();
23 if (current >= limit) {
24 return false;
25 }
26 if (count.compareAndSet(current, current + 1)) {
27 return true;
28 }
29 }
30 }
31 
32 public int current() {
33 return count.get();
34 }
35 
36 public int reset() {
37 return count.getAndSet(0);
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1AtomicInteger gives you thread-safe counting without locks or synchronized blocks.
  2. 2A compareAndSet retry loop lets you enforce conditional updates atomically under contention.
  3. 3updateAndGet clamps values in place so a decrement never drops below its floor.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A thread-safe request counter with AtomicInteger — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code