Sub topic 9
Don't Pool Virtual Threads: Limit Concurrency with Semaphores
In the last chapter you learned that virtual threads help most with I/O-bound work, which is work that spends most of its time waiting. That raises a practical question. Suppose you start 10,000 virtual threads and each one wants to talk to the same database. The database might accept only 10 connections at once. How do you stop 10,000 threads from flooding it?
With platform threads, the usual answer was a thread pool. With virtual threads, the answer changes. This chapter explains why, and shows you the tool to use instead: the Semaphore.
Why We Used to Pool Threads
A thread pool is a fixed group of threads that are created once and reused for many tasks. You hand a task to the pool, and one of its threads runs it when that thread is free.
Pools solved two problems at the same time:
- Cost. Platform threads are expensive to create. Each one reserves a large stack and is backed by an operating system thread. Reusing threads saved that cost.
- Limits. A pool with 10 threads can run at most 10 tasks at once. That cap protected slow or small resources, such as a database.
Virtual threads remove the first problem completely. A virtual thread costs about as much as a small Java object. Creating a new one for every task is the intended way to use them.
That leaves only the second problem, limiting how many tasks touch a scarce resource. You still need that limit. You just need a different tool for it.
The Anti-Pattern: A Pool of Virtual Threads
You may be tempted to keep your old pool and simply fill it with virtual threads:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PooledVirtualThreads {
public static void main(String[] args) {
// Works, but this is the pattern to avoid
try (ExecutorService pool =
Executors.newFixedThreadPool(10, Thread.ofVirtual().factory())) {
for (int i = 0; i < 1_000; i++) {
int id = i;
pool.submit(() -> System.out.println("task " + id));
}
}
}
}This program runs, but it throws away what makes virtual threads useful.
- The limit lands in the wrong place. The pool caps everything the task does, not only the database call. If a task also parses JSON, calls a cache, and writes a log line, all of that waits behind the same 10-thread cap.
- Threads live too long. Pooled threads run task after task. Any value left in a thread local (covered in the next chapter) can leak from one task into the next.
- It hides intent. A reader sees "a pool of 10" and has to guess why. Was it for cost? For the database? Both?
What a Semaphore Is
A semaphore is a counter of permits. A permit is a ticket that allows one thread to go ahead. Java's version is java.util.concurrent.Semaphore.
It has two main methods:
acquire()takes one permit. If none are left, the thread waits until one is returned.release()gives one permit back, which lets a waiting thread continue.
If you create new Semaphore(10), at most 10 threads can hold a permit at the same moment. The eleventh thread waits.
Waiting is where virtual threads shine. When a virtual thread blocks in acquire(), it unmounts from its carrier thread, as you saw in the chapter on carrier threads. Waiting costs almost nothing. You can have 990 virtual threads parked at the semaphore while 10 do real work, and your CPU cores stay free for other tasks.
The Pattern: One Thread per Task, a Semaphore per Resource
Here is the recommended shape. Every task gets its own virtual thread. Only the database call is guarded.
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class LimitedDatabaseCalls {
private static final Semaphore PERMITS = new Semaphore(10);
static String query(int id) throws InterruptedException {
PERMITS.acquire();
try {
Thread.sleep(100); // stands in for a database call
return "row " + id;
} finally {
PERMITS.release();
}
}
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000; i++) {
int id = i;
executor.submit(() -> query(id));
}
}
}
}Read it step by step:
new Semaphore(10)creates 10 permits. That number matches what the database can handle.newVirtualThreadPerTaskExecutor()starts one fresh virtual thread for each of the 1,000 tasks.- Inside
query, each thread callsacquire()before the database call. - The
finallyblock always callsrelease(), even if the call throws an exception. - Closing the executor at the end of the
tryblock waits for all tasks to finish.
The program takes about 10 seconds: 1,000 calls, 10 at a time, 100 milliseconds each.
Proving the Limit Works
It helps to see the cap with your own eyes. This version counts how many tasks are inside the guarded section at once and records the highest count it sees.
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public class WatchThePermits {
private static final Semaphore PERMITS = new Semaphore(10);
private static final AtomicInteger inUse = new AtomicInteger();
private static final AtomicInteger maxSeen = new AtomicInteger();
static void callService() throws InterruptedException {
PERMITS.acquire();
try {
int now = inUse.incrementAndGet();
maxSeen.accumulateAndGet(now, Math::max);
Thread.sleep(100); // pretend to call a slow service
} finally {
inUse.decrementAndGet();
PERMITS.release();
}
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 200; i++) {
executor.submit(() -> {
callService();
return null;
});
}
}
long elapsed = System.currentTimeMillis() - start;
System.out.println("Highest concurrent calls: " + maxSeen.get());
System.out.println("Elapsed ms: " + elapsed);
}
}An AtomicInteger is a number that many threads can safely change at the same time. The program prints Highest concurrent calls: 10 and an elapsed time a little over 2,000 milliseconds (200 tasks, 10 at a time, 100 ms each). Change the semaphore to 50 permits and run it again. The highest count becomes 50 and the time falls to about 400 ms.
The task returns null so the lambda counts as a Callable. A Callable is allowed to throw checked exceptions such as InterruptedException. A Runnable is not.
Not Waiting Forever: tryAcquire with a Timeout
Sometimes waiting a long time is worse than failing quickly. A web request that waits 30 seconds for a database slot has probably been abandoned by its user anyway. tryAcquire lets you give up after a set time.
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class TimeoutExample {
private static final Semaphore PERMITS = new Semaphore(2);
static String fetch(int id) throws InterruptedException {
if (!PERMITS.tryAcquire(200, TimeUnit.MILLISECONDS)) {
return "busy, try later (" + id + ")";
}
try {
Thread.sleep(500); // slow call
return "data " + id;
} finally {
PERMITS.release();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[5];
for (int i = 0; i < threads.length; i++) {
int id = i;
threads[i] = Thread.ofVirtual().start(() -> {
try {
System.out.println(fetch(id));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
for (Thread t : threads) {
t.join();
}
}
}Two tasks get permits and print data. The other three wait 200 ms, find no free permit, and print busy, try later. Only call release() when tryAcquire returned true. If you release a permit you never got, the count goes up and your limit silently grows.
Choosing the Right Tool
| Need | Platform-thread habit | Virtual-thread approach |
|---|---|---|
| Avoid thread creation cost | Reuse threads in a pool | Not needed: create a new virtual thread per task |
| Cap calls to a database or API | Size the pool to the limit | `Semaphore` around that call only |
| Give up if the resource is busy | Bounded queue with rejection | `tryAcquire(timeout, unit)` |
| Different limits for different resources | Several separate pools | One semaphore per resource |
| Fresh state for each task | Clear thread locals by hand | Automatic, since every thread is new |
A few more details are useful to know:
- Fairness.
new Semaphore(10, true)makes a fair semaphore, which hands out permits in the order threads asked. The default is unfair. Unfair is a little faster, but a single waiting thread can be passed over many times. Choose fair when steady response times matter more than raw speed. - Connection pools are still fine. A database connection pool, such as HikariCP, pools connections, not threads. Connections really are expensive. Keep the connection pool. Its size already acts as a limit, so a separate semaphore is often unnecessary for that database.
- Pick the number from the resource. The permit count should come from what the downstream system can handle. The number of CPU cores is the wrong basis.
Exercises
Exercise
A teammate writes Executors.newFixedThreadPool(20, Thread.ofVirtual().factory()) so their service never makes more than 20 calls to a partner API at once. Each task also does local work that does not use the API. Why is this a poor choice, and what should they write instead?
Show answer
The pool caps the whole task, so the local work also waits behind the 20-thread limit. Pooled threads are also reused, so thread-local state can leak from one task to the next. They should use Executors.newVirtualThreadPerTaskExecutor() and wrap only the partner API call in Semaphore.acquire(), with release() in a finally block on a Semaphore with 20 permits.
Exercise
In this code, what goes wrong if callApi() throws an exception? PERMITS.acquire(); callApi(); PERMITS.release();
Show answer
When callApi() throws, release() never runs, so the permit is lost. After enough failures every permit is gone, and every later call to acquire() waits forever. The fix is to call acquire(), then put callApi() in a try block with PERMITS.release() in its finally block.
Exercise
In WatchThePermits, you change the semaphore to 25 permits and keep 200 tasks of 100 ms each. About how long does the program take, and what is the highest concurrent count?
Show answer
The highest count is 25. The 200 tasks run in 200 / 25 = 8 rounds of 100 ms, so the program takes about 800 ms plus a little startup time.