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
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 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.