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
public class TimedFetchService { private final ExecutorService executor = Executors.newFixedThreadPool(8); private final HttpClient httpClient = HttpClient.newHttpClient();
Enforcing HTTP timeouts with a Future
concurrency
timeouts
thread-pool
Intermediate
8 steps
java
@Component public class RefreshTokenSuccessHandler implements AuthenticationSuccessHandler { private final RefreshTokenService refreshTokenService;
Issuing JWT and refresh tokens on login in Spring
authentication
jwt
http-cookies
Intermediate
7 steps
java
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule;
Serializing Money to JSON in Spring
serialization
jackson
money
Intermediate
8 steps
javascript
import { unstable_cache, revalidateTag } from 'next/cache' import { db } from '@/lib/db' export const getDashboardStats = unstable_cache(
Caching dashboard stats in Next.js
caching
cache-invalidation
tag-based-revalidation
Intermediate
8 steps
java
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class TenantResolutionFilter extends OncePerRequestFilter {
How a tenant-resolution filter works in Spring
multi-tenancy
servlet-filter
thread-local
Intermediate
8 steps
java
@Repository public interface SubscriptionRepository extends JpaRepository<Subscription, Long> { @Modifying(clearAutomatically = true, flushAutomatically = true)
Bulk JPQL updates in a Spring Data repository
jpql
bulk-update
modifying-query
Intermediate
5 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.