Sub topic 9
Don't Pool Virtual Threads: Limit Concurrency with Semaphores
You now know that virtual threads are cheap, so you can create one for every task. Your program still talks to things that are not cheap. A database might accept only 10 connections. A partner's web service might allow only 20 calls at once. This chapter shows how to protect those resources without giving up one virtual thread per task.
The old habit: a fixed-size pool
With platform threads, people often wrote code like this:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class OldHabit {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1_000; i++) {
int id = i;
pool.submit(() -> System.out.println("task " + id));
}
pool.shutdown();
}
}A thread pool is a group of threads that the program reuses for many tasks. A fixed-size pool of 10 threads did two jobs at once:
- It saved the cost of creating expensive platform threads.
- It made sure no more than 10 tasks ran at the same time.
The first job no longer matters for virtual threads, because they are cheap to create. The second job still matters. A pool is a clumsy way to do it, though.
Why pooling virtual threads is a mistake
A virtual thread is meant to live for one task and then end. If you put virtual threads in a pool, you bring back the problems they were built to fix:
- Tasks wait in a queue even when they don't need the scarce resource.
- One thread is reused for many tasks, so leftover data from one task can leak into the next.
- The limit applies to the whole task, not just the part that touches the database.
What you really want is to limit access to the resource, not the number of threads.
The better tool: a semaphore
A semaphore is an object that holds a fixed number of permits. A permit is a ticket that lets one thread pass. A thread calls acquire() to take a permit. If none are left, the thread waits. When it is done, it calls release() to give the permit back.
When a virtual thread waits in acquire(), it is blocked, and blocking a virtual thread is cheap. It unmounts from its carrier thread, and the carrier goes on to run other work.
A worked example
This program starts 1,000 virtual threads. Each one runs a fake database query. The semaphore allows only 10 queries at a time.
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) {
long start = System.currentTimeMillis();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000; i++) {
int id = i;
executor.submit(() -> query(id));
}
}
long elapsed = System.currentTimeMillis() - start;
System.out.println("Finished in about " + elapsed + " ms");
}
}Each query takes 100 ms, and 10 run at once. So 1,000 queries take about 100 rounds of 100 ms, roughly 10 seconds. The database never sees more than 10 calls at the same time.
Here is what each part does:
| Part | Job |
|---|---|
| `new Semaphore(10)` | Creates 10 permits |
| `PERMITS.acquire()` | Takes a permit, or waits for one |
| `try` / `finally` | Makes sure the permit is returned even if the query fails |
| `PERMITS.release()` | Gives the permit back |
Exercises
Exercise
Why is a fixed-size pool of virtual threads a poor way to limit database calls?
Show answer
Virtual threads are cheap and meant to be used once per task, so pooling them gives no savings. A pool also limits whole tasks instead of just the database call, and reused threads can carry leftover data from one task to the next. A semaphore limits only the database access.
Exercise
In the example, you change new Semaphore(10) to new Semaphore(50). About how long will the 1,000 queries take now?
Show answer
About 2 seconds. With 50 queries running at once, 1,000 queries need 20 rounds of 100 ms.
Exercise
What goes wrong if you call PERMITS.release() right after Thread.sleep(100) instead of in a finally block?
Show answer
If the sleep or query throws an exception, release() never runs and the permit is lost. Once enough permits are lost, acquire() blocks forever and the program stops making progress.