skip to content

How does a Java virtual thread run on carrier threads, and what happens when it mounts and unmounts?

level: seniorimportance: must knowfreq 70%

answer

  1. Carrier = real platform/OS thread from a (default) ForkJoinPool
  2. Mount = run virtual thread on a carrier; unmount on blocking
  3. Unmount copies the continuation (stack) to the heap, frees carrier
  4. Remount may use a different carrier; resumes after the blocking call
  5. Pinning: native frames; synchronized only before 24

basics

~20 s

A virtual thread has no OS thread of its own; the JVM mounts it on a carrier platform thread to run. On most JDK blocking calls it unmounts: its stack moves to the heap and the carrier runs other virtual threads.

solid answer

~50 s

A virtual thread is scheduled by the JVM, not the OS. To execute, the JVM mounts it onto a carrier thread — a platform (OS) thread from a pool, by default a dedicated ForkJoinPool. While mounted, the virtual thread's stack frames live on the carrier's native stack and it runs like ordinary code. When it hits a blocking call that the JDK has instrumented (e.g. socket I/O, locks, sleep; most file-system calls hold the carrier instead), the JVM unmounts it: it copies the continuation — the virtual thread's stack and execution state — onto the heap, and releases the carrier to run a different virtual thread. When the awaited event completes, the scheduler remounts the virtual thread, possibly onto a different carrier, restoring its stack, and it resumes right after the blocking call. So one carrier multiplexes many virtual threads: while some wait, others run. The number of carriers is small (defaults to the CPU core count), while virtual threads can number in the millions.

code

java · 21 lines
java
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class Mounting {
    public static void main(String[] args) {
        // One virtual thread per task; a few carrier threads run them all.
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            IntStream.range(0, 100_000).forEach(i -> executor.submit(() -> {
                String before = Thread.currentThread().toString();
                Thread.sleep(Duration.ofSeconds(1)); // unmounts: the carrier runs other virtual threads
                String after = Thread.currentThread().toString();
                if (i == 0) {
                    System.out.println(before); // e.g. VirtualThread[#25]/runnable@ForkJoinPool-1-worker-1
                    System.out.println(after);  // the carrier after the sleep may be a different worker
                }
                return i;
            }));
        } // close() waits for all 100,000 tasks
    }
}

go deeper

for a junior

Knows a virtual thread runs on top of a real platform thread and that it 'steps aside' when it blocks.

for a middle

Describes mounting onto a carrier and unmounting on blocking, and that carriers are few while virtual threads are many.

for a senior

Explains the continuation being moved to the heap on unmount, remounting on a possibly-different carrier resuming after the blocking call, and names the default ForkJoinPool scheduler.

for a principal

Discusses pinning causes by JDK version and their mitigations, the scheduler's FIFO mode against the common pool's LIFO mode, carrier-pool sizing and tuning, and how library choices (native calls, file I/O, thread-locals, and synchronized before JDK 24) affect whether the mechanism actually scales.

## Two kinds of thread A **platform thread** is a Java thread mapped one-to-one to an **OS thread** — the unit the operating system schedules onto CPU cores. A **virtual thread** is a Java thread scheduled by the **JVM** (the Java runtime), and it is **not** permanently tied to any OS thread. This section explains the machinery that lets virtual threads run on a tiny number of OS threads. ## The carrier thread A virtual thread cannot touch a CPU by itself; only OS threads run on cores. So to execute, a virtual thread is **mounted** onto a **carrier thread** — an ordinary **platform (OS) thread** drawn from a pool. By default this pool is a dedicated **ForkJoinPool** (a work-stealing thread pool from `java.util.concurrent`) whose size defaults to the number of available processor cores. Think of carriers as a small set of 'workers' and virtual threads as a huge backlog of 'jobs' that take turns on those workers. ## Mounting **Mounting** means: the JVM picks an idle carrier and runs the virtual thread on it. While mounted, the virtual thread's **stack frames** (the per-method records of local variables and the call chain) sit on the carrier's native stack, and the code executes exactly like normal Java. From the CPU's point of view, the carrier is just running code. ## Unmounting on blocking The key trick happens when the virtual thread does something **blocking** — an operation that would normally make a thread wait, such as reading from a network socket, sleeping, or waiting on a lock. Most of the JDK's blocking operations have been **rewritten** so that, instead of blocking the carrier, they signal the JVM to **unmount** the virtual thread: 1. The JVM captures the virtual thread's current state — its stack and program position — as a **continuation** (a saved, resumable snapshot of an execution). 2. That continuation is **copied from the carrier's stack onto the heap** (the JVM's general-purpose memory). This is why an idle virtual thread costs only a small, growable chunk of heap rather than a full ~1 MB OS-thread stack. 3. The **carrier is released** back to the pool, free to mount and run a *different* virtual thread. So a blocking call no longer wastes an OS thread: the OS thread (carrier) goes off and does other useful work while the virtual thread 'waits' as inert heap data. Not every blocking call unmounts. **Many file-system operations** cannot, because of limits in the OS: they hold the carrier while they run, and some compensate by temporarily adding a platform thread to the scheduler, which may then grow past its parallelism up to `jdk.virtualThreadScheduler.maxPoolSize` (256 by default, or the parallelism if that is larger). ## Remounting and resuming When the awaited event finishes (the bytes arrive, the sleep elapses, the lock frees), the JVM scheduler **remounts** the virtual thread — possibly onto a **different** carrier than before. The continuation is restored from the heap back onto a carrier's stack, and execution **resumes at the exact instruction after the blocking call**. To your code it looks like an ordinary blocking call that simply returned; the unmount/remount is invisible. ## The default scheduler The default scheduler is a **work-stealing ForkJoinPool in FIFO mode**: when a virtual thread becomes runnable it is queued, carriers take queued work in first-in-first-out order, and an idle carrier steals work from a busy one. The common pool that parallel streams use runs in **LIFO** mode instead. The `ForkJoinPool` docs say FIFO mode (`asyncMode`) may suit pools whose workers only process event-style asynchronous tasks that are never joined, which is what a runnable virtual thread is. The scheduler does **not implement time sharing**: a running virtual thread is not preempted on a timer, so one that computes without blocking keeps its carrier. ## Pinning (the exception) Sometimes a virtual thread **cannot** be unmounted while blocked — it stays **pinned** to its carrier, tying up that OS thread. Which cases pin depends on the JDK: - **JDK 21 to 23:** blocking inside a `synchronized` block or method, and blocking in a native method or foreign function. The advice then was `java.util.concurrent.locks.ReentrantLock` around frequent, long blocking calls. - **JDK 24 and later, including 25 LTS and 27:** virtual threads hold monitors independently of their carriers (JEP 491), so `synchronized` no longer pins. Blocking while a native frame is on the stack still does, such as native code calling back into Java that blocks, and so do a few class-loading and class-initialization cases. JDK Flight Recorder's `jdk.VirtualThreadPinned` event reports a virtual thread that blocks while pinned. ## Putting it together A handful of carriers (≈ core count) **multiplex** millions of virtual threads: at any instant only a few run, the rest are parked as heap continuations. Because unmounting frees the carrier on most blocking calls, blocking code scales — exactly the property thread-per-request needs.

  • What is 'pinning' and what commonly causes it?
    Pinning is when a blocked virtual thread cannot unmount and keeps its carrier OS thread, which hurts scalability. On JDK 21 to 23 the classic causes were blocking inside synchronized code and in native methods or foreign functions, and the advice was ReentrantLock around long blocking calls. Since JDK 24 (JEP 491) synchronized no longer pins; blocking with a native frame on the stack still does.
  • Why does the virtual-thread scheduler run its ForkJoinPool in FIFO mode rather than the default LIFO mode?
    Both modes steal work; they differ in the order a worker takes its own queued tasks. LIFO, the stack-based default, suits recursive fork/join tasks that get joined. The ForkJoinPool docs say FIFO (asyncMode) may suit workers that only process event-style asynchronous tasks that are never joined, and a virtual thread made runnable again is such a task.

  • Saying each virtual thread keeps its own OS thread while blocked
  • Claiming the carrier stays busy/blocked during the virtual thread's wait
  • Confusing the carrier pool size (≈ cores) with the number of virtual threads (millions)
  • Forgetting pinning: assuming all blocking always unmounts cleanly

virtual threads
Java 21pre-release 19
synchronized no longer pins virtual threads
Java 24

Assumes JDK 27. Virtual threads were a preview in JDK 19 and 20 and are final since JDK 21. Synchronized code stopped pinning virtual threads in JDK 24 (JEP 491), so JDK 25 LTS behaves like 27 here; on JDK 21 to 23, blocking inside synchronized pins the carrier.

context