Sub topic 6
Under the Hood: Carrier Threads and Mounting
Earlier chapters showed that you can start thousands of virtual threads and they finish quickly, even when every one of them sleeps. This chapter explains how the JVM does that. You will learn what a carrier thread is, what it means for a virtual thread to be mounted and unmounted, and which part of the JVM decides where each virtual thread runs. Two small programs let you watch it happen on your own machine.
Three Words You Need
Three new terms come up again and again in this chapter.
- A carrier thread is a normal platform thread that runs a virtual thread's code. The virtual thread "rides on" the carrier, the way a passenger rides in a car.
- Mounting is the moment a virtual thread is placed onto a carrier thread so its code can run.
- Unmounting is the moment a virtual thread is taken off its carrier. The virtual thread is paused, and the carrier is free to run a different virtual thread.
A fourth term ties them together. The scheduler is the part of the JDK that decides which virtual thread gets mounted on which carrier, and when.
The Big Picture
Picture a small team of workers (the carriers) and a long line of jobs (the virtual threads). Each worker takes a job from the line and works on it. If the job has to wait for something, like a reply from a database, the worker does not stand around. The worker puts that job aside and takes the next one from the line. When the reply arrives, the paused job goes back into the line, and any free worker can continue it.
Because of this design, 10,000 virtual threads do not need 10,000 operating system threads. A handful of carriers can serve all of them, as long as most of the virtual threads spend most of their time waiting.
The Scheduler: A Fork/Join Pool
The default scheduler is a ForkJoinPool. A thread pool is a group of reusable threads that run tasks, and ForkJoinPool is one of Java's built-in pool types. The virtual thread scheduler uses its own pool, separate from the common pool used by parallel streams.
Here are the main facts about this pool:
| Property | Default value | What it means |
|---|---|---|
| Number of carriers (parallelism) | Number of CPU cores the JVM sees | How many virtual threads can run at the same instant |
| Order of work | First in, first out | Virtual threads that became ready earlier tend to run earlier |
| Maximum pool size | 256 | Upper limit if the pool must add extra carriers temporarily |
| Carrier names | `ForkJoinPool-1-worker-1`, `-2`, and so on | Names you will see in output and thread dumps |
The scheduler shares out time on the carriers. It does not split time into fixed slices. A virtual thread runs on its carrier until it blocks (waits for something) or finishes. Only then does the carrier move on to another virtual thread. This is why virtual threads suit work that waits a lot and suit heavy calculation less well. A later chapter covers that choice in detail.
What Happens During Mounting and Unmounting
Every thread has a stack. A stack is the memory where a thread keeps its local variables and keeps track of which method called which. A platform thread's stack is a large, fixed block of memory owned by the operating system. A virtual thread's stack works differently.
When a virtual thread blocks, for example inside Thread.sleep() or while reading from a network socket, the JVM does three things:
- It copies the virtual thread's stack frames (the stored data for each method call in progress) off the carrier and into the Java heap. The heap is the ordinary memory where Java objects live.
- It marks the virtual thread as parked, meaning paused and waiting.
- It frees the carrier, which immediately picks up another virtual thread from the queue.
When the thing it waited for is ready (the sleep ends or the data arrives), the virtual thread is put back in the scheduler's queue. A free carrier mounts it, the needed stack frames are copied back, and the code continues from the exact line where it stopped. Your code does not notice any of this. It just looks like a method call that took a while to return.
Stack frames stored in the heap take only as much memory as the thread actually uses. A virtual thread with a short call chain needs only a few hundred bytes. Platform threads usually reserve around a megabyte each. This difference is why millions of virtual threads can fit in memory at once.
Watching a Virtual Thread Change Carriers
When you print a virtual thread, its text includes the carrier it is currently mounted on, after the @ sign. The program below prints each task's thread before and after a short sleep.
import java.time.Duration;
import java.util.concurrent.Executors;
public class CarrierHop {
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 4; i++) {
int id = i;
executor.submit(() -> {
System.out.println("task " + id + " before: " + Thread.currentThread());
Thread.sleep(Duration.ofMillis(100));
System.out.println("task " + id + " after: " + Thread.currentThread());
return null;
});
}
}
}
}The output will look something like this. Your numbers will differ.
task 0 before: VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1
task 1 before: VirtualThread[#23]/runnable@ForkJoinPool-1-worker-2
task 2 before: VirtualThread[#24]/runnable@ForkJoinPool-1-worker-3
task 3 before: VirtualThread[#25]/runnable@ForkJoinPool-1-worker-4
task 0 after: VirtualThread[#21]/runnable@ForkJoinPool-1-worker-3
task 1 after: VirtualThread[#23]/runnable@ForkJoinPool-1-worker-1
task 2 after: VirtualThread[#24]/runnable@ForkJoinPool-1-worker-2
task 3 after: VirtualThread[#25]/runnable@ForkJoinPool-1-worker-4Look at task 0. Its virtual thread number, #21, stays the same, so it is still the same thread. Before the sleep it ran on worker-1. After the sleep it ran on worker-3. The virtual thread was unmounted during the sleep and later mounted on whichever carrier was free.
Counting How Many Carriers Do the Work
The next program starts 10,000 virtual threads and records the name of every carrier any of them ran on. It reads the carrier name from the text after @. That text format is meant for people to read, not for programs, so use this trick for learning only and never in real code.
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
public class CountCarriers {
public static void main(String[] args) {
Set<String> carriers = ConcurrentHashMap.newKeySet();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(10));
String text = Thread.currentThread().toString();
int at = text.indexOf('@');
if (at >= 0) {
carriers.add(text.substring(at + 1));
}
return null;
});
}
}
System.out.println("Virtual threads started: 10000");
System.out.println("Carrier threads used: " + carriers.size());
System.out.println("Available processors: " + Runtime.getRuntime().availableProcessors());
}
}On an 8-core machine, a typical result is:
Virtual threads started: 10000
Carrier threads used: 8
Available processors: 8That works out to 10,000 virtual threads on 8 carriers. The set is a ConcurrentHashMap key set because many threads add to it at the same time, and an ordinary HashSet is not safe for that.
Changing the Number of Carriers
You can change the scheduler's settings with system properties. A system property is a setting you pass to the JVM with -D when you start a program. The most useful one sets how many carriers there are:
java -Djdk.virtualThreadScheduler.parallelism=2 CountCarriers.javaNow the program reports that it used 2 carriers, and it still finishes in about the same time. The tasks spend their time sleeping, and sleeping does not need a carrier.
| System property | Controls |
|---|---|
| `jdk.virtualThreadScheduler.parallelism` | Number of carriers normally running |
| `jdk.virtualThreadScheduler.maxPoolSize` | Most carriers the pool may ever create |
When a Virtual Thread Cannot Unmount
Mounting and unmounting only help if the virtual thread can actually leave its carrier while it waits. In a few situations it cannot, and it keeps the carrier busy while doing nothing. This is called pinning. One example is calling native code, meaning code written in a language like C and called from Java. On JDK 21 to 23, blocking inside a synchronized block also pins. If too many virtual threads are pinned at once, the few carriers fill up and everything else waits. The pinning chapter explains how to spot and fix it. For now, remember that the cheap waiting described in this chapter depends on the virtual thread being free to unmount.
Summary
- Virtual threads run on a small set of platform threads called carrier threads.
- The scheduler is a dedicated
ForkJoinPoolwith one carrier per CPU core by default. - When a virtual thread blocks, it unmounts: its stack moves to the heap and the carrier runs other work.
- When it becomes ready, any free carrier mounts it again, and it continues where it stopped.
Thread.currentThread()returns the virtual thread, and the carrier stays hidden.
Exercise
In the CarrierHop output, task 0 printed "@ForkJoinPool-1-worker-1" before sleeping and "@ForkJoinPool-1-worker-3" after. Explain what happened during the sleep.
Show answer
When task 0 called Thread.sleep, its virtual thread unmounted. Its stack frames were saved in the heap and worker-1 was freed to run other virtual threads. When the sleep ended, the virtual thread went back into the scheduler queue, and worker-3 happened to be free, so the scheduler mounted it there. The virtual thread number (#21) stayed the same because it was still the same virtual thread.
Exercise
You run CountCarriers with -Djdk.virtualThreadScheduler.parallelism=1. About how many carriers will it report, and will the program take much longer? Why?
Show answer
It will report 1 carrier. It will not take much longer, because each task spends almost all its time sleeping, and a sleeping virtual thread is unmounted and does not use the carrier. The single carrier only has to do the tiny bits of work before and after each sleep.
Exercise
Why can a JVM hold far more virtual threads in memory than platform threads?
Show answer
A platform thread reserves a large, fixed stack from the operating system, often about a megabyte. A virtual thread's stack frames live in the Java heap and take only as much space as the thread actually uses, often a few hundred bytes for a short call chain. Thousands or millions of small heap objects fit where only a few thousand large stacks would.