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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1AtomicInteger gives you thread-safe counting without locks or synchronized blocks.
- 2A compareAndSet retry loop lets you enforce conditional updates atomically under contention.
- 3updateAndGet clamps values in place so a decrement never drops below its floor.
Related explainers
java
@RestController @RequestMapping("/api/users") public class UserController {
How a Spring REST controller maps users
rest-api
dependency-injection
dto-mapping
Intermediate
7 steps
go
package fetch import ( "context"
Concurrent API fetches with errgroup in Go
concurrency
goroutines
error-handling
Intermediate
8 steps
python
import threading import logging logger = logging.getLogger(__name__)
A self-rescheduling periodic task in Python
threading
scheduling
concurrency
Intermediate
6 steps
go
package pipeline import ( "context"
A cancelable worker pool in Go
concurrency
channels
worker-pool
Advanced
8 steps
java
@Service public class ReportGenerationService { private final ReportRepository reportRepository;
Async report generation with Spring @Async
async
dependency-injection
completablefuture
Intermediate
7 steps
java
package com.example.billing; import java.math.BigDecimal; import java.math.RoundingMode;
Locale-aware currency formatting in Java
internationalization
rounding
immutability
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-thread-safe-request-counter-with-atomicinteger-explained-java-0f73/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.