Sub topic 4
Carrier threads: how virtual threads run
This chapter assumes you know Java 21 basics, ExecutorService, and the idea that a virtual thread is a lightweight Thread managed by the JVM. It explains what actually executes a virtual thread, and why that matters when you tune or debug a Spring Boot application.
The two layers of threads
A virtual thread does not run by itself. The JVM needs an operating system (OS) thread to execute its instructions. That OS-backed thread is called a carrier thread. A carrier is an ordinary platform thread, and it belongs to a scheduler that the JDK creates for you.
Two layers are involved:
- Virtual threads. There can be thousands or millions of them. Each one holds a stack of frames and a state, and it lives on the Java heap while it is not running.
- Carrier threads. There are only a few of them. By default there is about one per CPU core. They do the real work on the CPU.
The JVM runs many virtual threads on a few carriers. This is sometimes called M:N scheduling, because M virtual threads share N carriers.
Mounting and unmounting
Running a virtual thread on a carrier is called mounting. Taking it off is called unmounting.
- A virtual thread is ready to run, so the scheduler picks a free carrier.
- The JVM mounts the virtual thread. Its stack frames are copied into the carrier's stack as needed, and your code runs.
- The code calls a blocking operation, such as reading from a socket or waiting on a
BlockingQueue. - The JDK sees that the call would block. It unmounts the virtual thread and copies its stack frames to the heap.
- The carrier is now free and picks another ready virtual thread.
- When the I/O completes, the virtual thread becomes ready again. Some carrier mounts it, not always the same one, and it continues after the blocking call.
The point of step 4 is that a blocked virtual thread does not hold a carrier. The code you write still looks blocking. The JDK turns the wait into a pause that costs almost nothing.
The scheduler behind the carriers
The JDK runs the carriers in a ForkJoinPool that it owns. You do not create it and you cannot replace it with a public API in Java 21. It runs in first-in, first-out (FIFO) mode, unlike the common pool.
Three system properties control its size:
| Property | Default | Meaning |
|---|---|---|
| `jdk.virtualThreadScheduler.parallelism` | Number of available processors | Target number of carriers running at once |
| `jdk.virtualThreadScheduler.maxPoolSize` | 256 | Upper limit on carriers, used when the pool compensates for blocked carriers |
| `jdk.virtualThreadScheduler.minRunnable` | Half of parallelism | Minimum number of carriers kept runnable when compensating |
Most applications should leave these alone. The default of one carrier per core fits the workload: virtual threads spend most of their time waiting and unmounted, so a few carriers can serve very many of them.
Carrier threads are daemon threads, and they are named ForkJoinPool-1-worker-N. A virtual thread by default has an empty name. You will see both in logs, as the next example shows.
Seeing the carrier
Printing a virtual thread shows the carrier it is mounted on. Here is a small program you can run on Java 21 or later:
import java.time.Duration;
import java.util.concurrent.Executors;
public class CarrierDemo {
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 3; i++) {
int id = i;
executor.submit(() -> {
System.out.println("before sleep " + id + ": " + Thread.currentThread());
try {
Thread.sleep(Duration.ofMillis(200));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("after sleep " + id + ": " + Thread.currentThread());
});
}
}
}
}A line of output looks like this:
before sleep 0: VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1
after sleep 0: VirtualThread[#21]/runnable@ForkJoinPool-1-worker-3The part after @ names the carrier. The virtual thread kept its identity, #21, but it may resume on a different carrier after the sleep. That is normal and safe. The JVM guarantees that your code sees one consistent thread.
The Thread.sleep call is a blocking operation that the JDK knows how to unmount. While the sleep lasts, the carrier runs other virtual threads.
What this means in Spring Boot
With spring.threads.virtual.enabled=true, Tomcat or Jetty starts a new virtual thread for each request. Your controller runs on that virtual thread. When it calls JDBC or an HTTP client and the call blocks on a socket, the virtual thread unmounts and its carrier serves another request.
You can check this with a handler that prints the thread:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class CarrierController {
@GetMapping("/carrier")
String carrier() {
return Thread.currentThread().toString();
}
}The response looks like VirtualThread[#52,tomcat-handler-3]/runnable@ForkJoinPool-1-worker-2. Tomcat names its virtual threads, and the carrier appears after @.
Two consequences follow:
- The number of concurrent requests is no longer limited by the carrier count. Thousands of requests can wait on I/O at once, while a handful of carriers do the CPU work between waits.
- CPU-bound work is still limited by cores. If a request computes for a long time without blocking, it keeps its carrier. With one carrier per core, a few such requests can occupy every carrier.
No time slicing
Virtual threads are scheduled cooperatively. A platform thread can be preempted by the OS at any moment. A virtual thread is not preempted by the JDK scheduler. It leaves its carrier only when it blocks, yields, or finishes.
Consider a virtual thread that runs a tight loop with no blocking call:
long sum = 0;
for (long i = 0; i < 50_000_000_000L; i++) {
sum += i;
}This thread holds its carrier for the whole loop. If you start as many of these as there are carriers, no other virtual thread can run until one finishes. The OS still schedules the carriers themselves, so the machine stays responsive, but the virtual threads that are waiting for a carrier do not get CPU time.
This is the main reason the chapter on workload fit warns against moving CPU-heavy work to virtual threads and expecting a gain. A virtual thread makes waiting cheap. It does not make computing faster.
When a virtual thread cannot unmount
Not every blocking call lets the virtual thread unmount. In two cases the virtual thread stays attached to its carrier while it waits:
- It blocks inside a
synchronizedblock or method on Java 21. - It blocks while a native method or a foreign function call is on its stack.
This is called pinning. A pinned virtual thread holds its carrier during the wait, which wastes that carrier. The JDK may add a temporary extra carrier in some blocking cases, such as Object.wait(), up to maxPoolSize, but it does not do so for every pinned wait. The pinning chapter covers the causes, the diagnosis, and the fixes. For now, remember that the carrier model only pays off when virtual threads can unmount.
Common mistakes
- Sizing the carrier pool to match request volume. Raising
parallelismto 1000 does not help I/O-bound code. It adds OS threads and context switching. Keep the default unless a measurement tells you otherwise. - Pooling virtual threads. Virtual threads are cheap, so create one per task. A fixed pool of virtual threads only adds a limit you do not need. If you need a limit, use a
Semaphore, which a later chapter covers. - Using the carrier's identity. Code should not depend on which carrier runs it. The carrier can change at every blocking call.
- Assuming fairness for long computations. Without time slicing, a long CPU loop can delay other virtual threads. Keep such work on a separate platform-thread executor.
Summary of the model
| Term | Meaning |
|---|---|
| Virtual thread | A `Thread` managed by the JVM, with its stack stored on the heap when idle |
| Carrier thread | A platform thread in the JDK's `ForkJoinPool` that runs a mounted virtual thread |
| Mount | The scheduler starts running a virtual thread on a carrier |
| Unmount | A virtual thread blocks, and its frames move to the heap so the carrier is free |
| Pinning | The virtual thread cannot unmount and keeps its carrier while it waits |
Exercise
Your Spring Boot service runs on a 4-core machine with virtual threads enabled. Under load, 2,000 requests wait on slow database calls, and the service still answers other requests quickly. Then a new endpoint is added that runs a 30-second pure computation loop with no blocking calls. After four users call it at the same time, all other endpoints stop responding. Explain why, using the carrier model, and name one fix.
Show answer
The default scheduler uses about one carrier per core, so there are 4 carriers. Waiting database calls are fine because those virtual threads unmount and free their carriers. The computation loop never blocks, and virtual threads are not preempted, so each of the four calls keeps one carrier for 30 seconds. All 4 carriers are busy, and other virtual threads, even ones whose I/O has finished, wait for a free carrier. A fix is to run the computation on a bounded platform-thread executor, so it does not use carriers, or to limit how many of these calls run at once with a Semaphore. Raising the carrier count is not a good fix, because it adds OS threads without adding cores.
Exercise
A log line shows VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1 before a database call, and VirtualThread[#21]/runnable@ForkJoinPool-1-worker-3 after it. Is this a bug? What does it show?
Show answer
It is not a bug. The virtual thread (#21) unmounted from worker-1 when the database call blocked, and later a different carrier, worker-3, mounted it to continue. The virtual thread keeps its identity and its stack, so the code sees no difference. It also shows that carriers are shared and that code must not depend on a particular carrier.