Limiting Concurrency With Virtual Threads: Semaphores and Rate Limiting in Java
Virtual threads remove the thread pool's built-in cap, so scarce resources need explicit protection. How to use java.util.concurrent.Semaphore as a bulkhead, with timeouts, fairness and the release-only-if-acquired rule, and how a concurrency limit differs from a requests-per-second rate limit.
kvi5hnuCode Sprout team member8 min readOn this page
A thread pool used to protect your downstream systems by accident. With 200 platform threads, a database never saw more than 200 concurrent queries from that application, because there were only 200 threads to send them. Virtual threads remove that accident. A server can now accept 50,000 requests at once, and if every one of them calls the same partner API, the partner sees 50,000 concurrent calls. Most systems don't survive that.
So with virtual threads, limits become explicit: you put them in front of the resource that needs them, not on the number of threads. The standard tool is a semaphore.
Semaphores in a nutshell
A java.util.concurrent.Semaphore holds a number of permits:
| Method | Effect |
|---|---|
acquire() | takes a permit, waiting if none is free; throws InterruptedException |
tryAcquire() | takes a permit only if one is free right now; returns true or false |
tryAcquire(timeout, unit) | waits at most the timeout for a permit |
release() | returns a permit, waking one waiting thread |
availablePermits() | the number of free permits at this moment |
new Semaphore(n, true) | a fair semaphore: waiters get permits in arrival order |
Wrap each use of a limited resource in acquire/release, and at most n threads use it at once. The rest wait. With virtual threads, waiting in acquire() unmounts the thread, so thousands of waiting callers cost only a little heap.

This pattern is often called a bulkhead, after the walls that divide a ship's hull into compartments: if one compartment floods, the others stay dry. A slow partner API fills up its own bulkhead, while requests that don't need it keep flowing.
The one rule: release only what you acquired
A semaphore doesn't record which thread took a permit. Any thread can call release(), even one that never acquired, and each extra release permanently adds a permit. So a bug in the release logic silently raises your limit.
The safe pattern acquires before the try, so that finally runs only if the permit was actually taken:
permits.acquire(); // if this throws, we never enter try, so we never release
try {
return callPartner();
} finally {
permits.release();
}
A very common mistake puts acquire() inside the try. If acquire() throws, for example because the waiting thread is interrupted, finally releases a permit the thread never had. The demo below shows the effect.
A bulkhead in action
The program has three parts. First, 200 virtual threads call a partner API through a bulkhead of 10 permits, and the API records the most concurrent calls it ever saw. Second, a smaller bulkhead uses tryAcquire with a timeout so that callers give up instead of waiting forever. Third, it reproduces the acquire-inside-try bug:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
/** A downstream service that can handle only a few calls at once; it counts how many it sees. */
static class PartnerApi {
private final AtomicInteger active = new AtomicInteger();
private final AtomicInteger peak = new AtomicInteger();
String fetchPrice(int item) throws InterruptedException {
int now = active.incrementAndGet();
peak.accumulateAndGet(now, Math::max);
try {
Thread.sleep(50); // the call takes 50 ms
return "price-" + item;
} finally {
active.decrementAndGet();
}
}
}
/** Lets at most 'limit' callers use the API at the same time. */
static class Bulkhead {
private final Semaphore permits;
Bulkhead(int limit) { permits = new Semaphore(limit, true); } // fair: FIFO order
<T> T call(Callable<T> work) throws Exception {
permits.acquire(); // acquire BEFORE try
try {
return work.call();
} finally {
permits.release(); // released only if acquired
}
}
<T> T callOrGiveUp(Callable<T> work, long timeout, TimeUnit unit) throws Exception {
if (!permits.tryAcquire(timeout, unit)) return null; // waited too long
try {
return work.call();
} finally {
permits.release();
}
}
}
public static void main(String[] args) throws Exception {
// 1. 200 virtual threads, but the partner never sees more than 10 calls at once
PartnerApi api = new PartnerApi();
Bulkhead bulkhead = new Bulkhead(10);
List<Future<String>> results = new ArrayList<>();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 200; i++) {
int item = i;
results.add(executor.submit(() -> bulkhead.call(() -> api.fetchPrice(item))));
}
}
System.out.println("1. calls completed: " + results.stream().filter(f -> f.resultNow() != null).count()
+ ", peak concurrent calls seen by the API: " + api.peak.get());
// 2. With a timeout: 30 callers, 5 permits, each call 50 ms, give up after 120 ms
PartnerApi slowApi = new PartnerApi();
Bulkhead small = new Bulkhead(5);
AtomicInteger served = new AtomicInteger(), rejected = new AtomicInteger();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 30; i++) {
int item = i;
executor.submit(() -> {
String r = small.callOrGiveUp(() -> slowApi.fetchPrice(item), 120, TimeUnit.MILLISECONDS);
(r == null ? rejected : served).incrementAndGet();
return r;
});
}
}
System.out.println("2. served " + served.get() + " of 30 within the timeout, gave up on " + rejected.get()
+ ", peak " + slowApi.peak.get());
// 3. The classic bug: acquire() inside try, so an interrupted acquire still releases
Semaphore gate = new Semaphore(1);
gate.acquire(); // someone holds the only permit
CountDownLatch waiting = new CountDownLatch(1);
Thread buggy = Thread.ofVirtual().start(() -> {
try {
waiting.countDown();
gate.acquire(); // blocks, then gets interrupted
// ... use the resource ...
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
gate.release(); // BUG: releases a permit it never got
}
});
waiting.await();
Thread.sleep(50);
buggy.interrupt();
buggy.join();
gate.release(); // the real holder releases its permit
System.out.println("3. permits after the bug: " + gate.availablePermits() + " (the semaphore was created with 1)");
}
}
Output (the split in line 2 depends on timing and may differ slightly):
1. calls completed: 200, peak concurrent calls seen by the API: 10
2. served 15 of 30 within the timeout, gave up on 15, peak 5
3. permits after the bug: 2 (the semaphore was created with 1)
What each part shows:
- The limit holds. 200 concurrent requests, but the API never saw more than 10 at once. The 200 calls took about 20 rounds of 50 ms, about a second, while the other 190 callers waited cheaply.
- Timeouts shed load. Five permits and 50 ms calls mean three rounds fit into 120 ms: 15 callers were served and 15 gave up. In a server, giving up means returning an error quickly (such as HTTP 503) instead of letting requests pile up. Under heavy overload, failing fast is kinder than everyone timing out.
- The bug raises the limit. The interrupted thread released a permit it never had, so a semaphore meant to allow one caller now allows two, and it stays that way. Repeated under load, such a bug quietly removes the protection altogether.
Fairness
new Semaphore(n, true) creates a fair semaphore: permits go to waiting threads in the order they arrived. A non-fair semaphore (the default) lets a newly arriving thread grab a just-released permit ahead of the queue, which is a little faster but can make some unlucky callers wait much longer than others. With thousands of waiting virtual threads, fairness usually matters more than the small cost, so the bulkhead above uses it. Note that tryAcquire() without a timeout ignores fairness and barges in if a permit is free.
Concurrency limits vs rate limits
A semaphore limits how many calls are in progress at the same time. Many external APIs state a different kind of limit: requests per time period, such as "100 requests per minute". The two are related through Little's Law (article 10): 10 concurrent calls that each take 50 ms produce up to 200 calls per second. But if calls become faster, a concurrency limit allows more calls per second, which may break a per-minute quota.
For a per-period limit, permits must expire with time instead of being returned. A simple version gives out a fixed number of permits per window and tops them up on a schedule:
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/** Allows at most 'permitsPerPeriod' calls to start in each period (a simple fixed window). */
public class RateLimiter implements AutoCloseable {
private final Semaphore permits;
private final int permitsPerPeriod;
private final ScheduledExecutorService refill = Executors.newSingleThreadScheduledExecutor();
public RateLimiter(int permitsPerPeriod, Duration period) {
this.permitsPerPeriod = permitsPerPeriod;
this.permits = new Semaphore(permitsPerPeriod);
long ms = period.toMillis();
refill.scheduleAtFixedRate(this::topUp, ms, ms, TimeUnit.MILLISECONDS);
}
private void topUp() {
int missing = permitsPerPeriod - permits.availablePermits();
if (missing > 0) permits.release(missing); // never exceed the per-period budget
}
/** Blocks until the call may start. Permits are not returned: they expire with the window. */
public void acquire() throws InterruptedException {
permits.acquire();
}
@Override public void close() { refill.shutdownNow(); }
public static void main(String[] args) throws Exception {
var startTimes = new java.util.concurrent.ConcurrentLinkedQueue<Long>();
long start = System.nanoTime();
try (var limiter = new RateLimiter(10, Duration.ofMillis(200))) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 35; i++) {
executor.submit(() -> {
limiter.acquire(); // wait for the window to allow it
startTimes.add((System.nanoTime() - start) / 1_000_000);
return null;
});
}
}
}
var perWindow = new java.util.TreeMap<Long, Integer>();
for (long ms : startTimes) perWindow.merge(ms / 200, 1, Integer::sum);
perWindow.forEach((w, n) -> System.out.println("window " + w + " (" + w * 200 + "-" + (w + 1) * 200 + " ms): " + n + " calls"));
}
}
Running it prints:
window 0 (0-200 ms): 10 calls
window 1 (200-400 ms): 10 calls
window 2 (400-600 ms): 10 calls
window 3 (600-800 ms): 5 calls
Thirty-five callers, but never more than ten starts per 200 ms window. A fixed window allows a burst at each window boundary (ten calls at the end of one window and ten at the start of the next). Production rate limiters usually use a token bucket or a sliding window to smooth that out. Libraries such as Resilience4j and Bucket4j provide well-tested implementations of bulkheads, rate limiters and circuit breakers. They're worth using instead of writing your own once the requirements grow.
Where to put limits
- In front of each scarce resource, not around whole requests. A request that only reads a cache shouldn't wait behind requests calling a slow payment provider.
- Connection pools are limits too. A JDBC pool such as HikariCP already caps concurrent queries at its pool size, and callers wait for a connection. With virtual threads that wait is cheap, but set a connection timeout so that waits don't grow without bound.
- Prefer failing fast under overload. Use
tryAcquirewith a timeout and return a clear error. Unlimited waiting turns a slow dependency into a slow everything. - Don't use a thread pool as the limit. A fixed pool of virtual threads would work, but it limits everything the pool runs, queues tasks invisibly, and hides the intent. A semaphore states exactly what is limited.
What's current
Semaphorehasn't changed in years. What changed with virtual threads is that blocking inacquire()is cheap, so semaphores became the standard way to bound concurrency.- Since Java 21, frameworks that switch to virtual threads (Spring Boot, Quarkus, Helidon) document the same advice: protect databases and remote services with connection pools, bulkheads and rate limiters instead of relying on a request thread pool.
Common questions
Why not just keep a fixed thread pool to limit load? A fixed pool limits all work equally and queues requests before they start, including the ones that don't touch the scarce resource. A semaphore around the resource limits only the calls that need it, and every request still gets its own cheap virtual thread.
Is Semaphore(1) the same as a lock?
It behaves like a non-reentrant lock: one thread at a time. But a semaphore has no owner, so another thread can release it, and the same thread can't acquire it twice without deadlocking. Use ReentrantLock for mutual exclusion and semaphores for counting.
Should the timeout be long or short?
Short enough that callers fail before their own callers give up. If the client times out after 2 seconds, a 30-second tryAcquire just wastes work. A few hundred milliseconds is common for interactive requests.
Does blocking in acquire() pin a virtual thread?
No. Semaphore is built on LockSupport.park, which unmounts the virtual thread, so waiting callers don't hold carriers.
Summary
- Virtual threads remove the implicit limit that thread pools placed on downstream systems, so limits must be explicit.
- A
Semaphorewith n permits lets at most n callers use a resource at once. Waiting virtual threads are unmounted and cheap. - Acquire before
tryand release infinally, so a failed or interrupted acquire never releases a permit it didn't get. tryAcquire(timeout, unit)lets callers fail fast under overload. Fair semaphores serve waiters in arrival order.- A concurrency limit isn't a rate limit. Per-period quotas need permits that expire with time, such as a fixed window or token bucket.
- Limit each scarce resource separately, and reuse proven libraries for advanced policies.
Practice questions
A semaphore has 3 permits. What does availablePermits() return after this code runs on one thread?
Semaphore s = new Semaphore(3);
s.acquire();
s.acquire();
s.release();
s.release();
s.release();
System.out.println(s.availablePermits());
Answer
4. Two permits were taken and three were released. A semaphore doesn't check that releases match acquires, so the extra release adds a fourth permit. This is why releases must happen only for permits actually acquired.
An API allows 600 requests per minute. Each call takes about 100 ms. Is new Semaphore(10) enough to stay within the quota?
Answer
No. Ten concurrent calls of 100 ms each can make up to 100 calls per second, which is 6,000 per minute, ten times the quota. A concurrency limit doesn't cap the rate. You need a rate limiter that allows 600 starts per minute (about 10 per second), possibly combined with a concurrency limit.
What's wrong with this method, and how do you fix it?
String fetch() throws InterruptedException {
try {
permits.acquire();
return client.get();
} finally {
permits.release();
}
}
Answer
If acquire() throws InterruptedException, finally still runs and releases a permit that was never acquired, raising the semaphore's limit. Move permits.acquire(); above the try, so the finally block only runs after a successful acquire.
Previous: How Java Virtual Threads Work Under the Hood: Mounting, Unmounting and Heap Stacks
Next: Virtual Thread Pinning in Java: synchronized, ReentrantLock and the Java 24 Fix

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.