Sub topic 3
Don't Pool Virtual Threads: Limit Concurrency with Semaphores
Limit Concurrency with Semaphores
A thread pool is a fixed group of threads that are reused for many tasks. Pools exist because platform threads are expensive. Virtual threads are cheap, so you should not pool them. Give each task its own virtual thread.
Sometimes a resource can only handle a few users at once. A database might accept only 10 connections. To protect it, use a semaphore. A semaphore is a counter of permits. A thread takes a permit before it uses the resource and gives the permit back afterward. When no permits are left, the next thread waits.
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));
}
}
}
}This program starts 1,000 virtual threads, and only 10 of them run the query at any moment.
Thread Locals When Threads Are Plentiful
A thread local is a variable that holds a separate value for each thread. If you have a million virtual threads, you can end up with a million copies. Keep the values small. Don't use thread locals to cache expensive objects, because virtual threads are not reused and the cache never gets a second hit.
Pinning
Pinning happens when a virtual thread cannot leave its carrier thread while it waits. The carrier is the platform thread that runs it. On JDK 21 to 23, blocking inside a synchronized block pins the virtual thread. JDK 24 fixed this case (JEP 491). On older JDKs, a ReentrantLock avoids the problem.
Seeing Virtual Threads
- A thread dump is a list of every thread and the code it is running. You can make one with
jcmd <pid> Thread.dump_to_file -format=json dump.json, and it includes virtual threads. - JDK Flight Recorder (JFR) is a built-in recorder of JVM events. It records the
jdk.VirtualThreadPinnedevent when pinning happens.
Migrating Existing Thread-Pool Code
| Old code | New code |
|---|---|
| `Executors.newFixedThreadPool(200)` | `Executors.newVirtualThreadPerTaskExecutor()` |
| Pool size used as a limit | `Semaphore` |
| Big cached thread locals | Plain local objects |
Looking Ahead
Structured concurrency is an API that treats a group of related tasks as one unit, so they finish or fail together. It is still a preview feature. Scoped values are a safer replacement for many uses of thread locals, and they became final in JDK 25.
Exercise
Your service calls an API that allows only 5 requests at a time. Should you use a pool of 5 virtual threads?
Show answer
No. Start one virtual thread per task and use a Semaphore with 5 permits around the API call.