How Java Virtual Threads Work Under the Hood: Mounting, Unmounting and Heap Stacks
What really happens when a Java virtual thread blocks: stack frames frozen into heap objects, the carrier freed, the poller or timer waiting for the event, and frames thawed onto any carrier when the thread resumes. Which JDK operations unmount, and why the carrier stays invisible.
kvi5hnuCode Sprout team member8 min readOn this page
From your code's point of view, a virtual thread is simply a thread: it calls methods, blocks, resumes and throws exceptions like any other. Underneath, the JDK does something quite different from an OS thread. This article follows a virtual thread through one blocking call to show where its stack lives, what happens to its carrier, and who wakes it up. Part 3 goes one level deeper, into the continuations that implement all of this.
Stacks on the heap
A platform thread's stack is a fixed block of address space, typically 1–2 MiB, reserved when the thread starts. The OS commits pages as the stack grows, and a thread keeps the pages it has touched (article 3). You have to guess the size in advance (-Xss), and a wrong guess wastes memory or causes StackOverflowError.
A virtual thread keeps its stack frames as ordinary objects on the Java heap, in structures called stack chunks. They start at a few hundred bytes and grow and shrink with the call stack, like an ArrayList. The garbage collector manages them, and when a virtual thread ends, its frames become garbage like any other object. There's nothing to size in advance, which is why a blocked virtual thread with a shallow stack costs about a kilobyte (article 8).
Mounting: borrowing a carrier
The operating system knows nothing about virtual threads. It only schedules platform threads. To run Java code, a virtual thread must be mounted on a carrier: one of the platform threads of the virtual-thread scheduler's ForkJoinPool.
Mounting means copying the virtual thread's frames onto the carrier's native stack so the CPU can execute them. The copy is lazy: only the topmost frames are copied, and deeper frames are brought over only if the code returns that far. While mounted, the virtual thread runs at full native speed. There's no interpretation and no overhead per instruction.
Unmounting: what happens when it blocks
When a mounted virtual thread calls a blocking operation, the JDK doesn't block the carrier. Instead:
- Freeze. The frames that changed are copied from the carrier's stack back into the heap stack chunk. This is the unmount.
- Register interest. The JDK arranges to be told when the operation can continue. A socket read registers the socket with a poller, a JDK component that asks the OS which sockets have data (using epoll on Linux, kqueue on macOS, I/O completion ports on Windows). A
sleepschedules a timer. A lock or queue records the waiting thread, to be woken by whoever releases it. - Free the carrier. The carrier returns to the scheduler and picks up the next ready virtual thread.
- Resume. When the data arrives, the timer fires or the lock is released, the virtual thread is put back in the scheduler's queue. The next free carrier, not necessarily the one it ran on before, thaws its top frames onto its stack and continues from the instruction after the blocking call.

The result is that waiting costs no thread at all. The only resources a waiting virtual thread holds are its heap objects and its registration with the poller or timer.
Which operations unmount
The JDK team rewrote the blocking parts of the standard library so they unmount virtual threads instead of blocking the carrier:
| Operation | On a virtual thread |
|---|---|
Thread.sleep, Thread.join, LockSupport.park | unmounts |
java.util.concurrent locks, queues, latches, semaphores, futures | unmounts (they're built on park) |
Socket I/O: Socket, ServerSocket, SocketChannel, DatagramSocket, and everything built on them, such as HttpClient, JDBC drivers and HTTP servers | unmounts |
Entering and waiting in synchronized, Object.wait() | unmounts since Java 24; pinned the carrier in Java 21–23 |
File I/O (FileInputStream, Files.read...) | doesn't unmount; holds the carrier for the (usually short) operation. Java 21–22 added a temporary carrier to compensate; since Java 23 only synchronous and direct-I/O writes do |
| Native code (JNI, the FFM API), class initialization | doesn't unmount (pins the carrier) |
The last three rows are the exceptions, covered in articles 13 and 14. For typical server code, where almost all waiting is network I/O and locks, the table's first rows are what matter, and they all unmount.
Watching it happen
This program does two things. First, it looks at a virtual thread while it's unmounted in Thread.sleep: its state, and its stack, which the JDK reads from the heap. Second, it runs 10,000 virtual threads that each note their carrier before and after a short sleep:
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
static final CountDownLatch inside = new CountDownLatch(1);
static String carrier() { // the carrier's name appears after '@' in toString()
String s = Thread.currentThread().toString();
return s.substring(s.indexOf('@') + 1);
}
static void handleRequest() throws InterruptedException { loadProfile(); }
static void loadProfile() throws InterruptedException { queryDatabase(); }
static void queryDatabase() throws InterruptedException {
inside.countDown();
Thread.sleep(500); // blocked: the virtual thread is unmounted here
}
public static void main(String[] args) throws Exception {
// Part 1: look at a virtual thread while it is unmounted
Thread vt = Thread.ofVirtual().name("request-42").start(() -> {
try { handleRequest(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
inside.await();
Thread.sleep(100); // let it reach sleep()
System.out.println("state while sleeping: " + vt.getState());
System.out.println("its stack, kept on the heap while unmounted:");
for (StackTraceElement frame : vt.getStackTrace()) {
if (frame.getClassName().equals("Solution")) System.out.println(" at " + frame.getMethodName());
}
vt.join();
// Part 2: 10,000 virtual threads note their carrier before and after a sleep
Set<String> carriers = ConcurrentHashMap.newKeySet();
AtomicInteger moved = new AtomicInteger();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> {
String before = carrier();
Thread.sleep(50);
String after = carrier();
carriers.add(before);
carriers.add(after);
if (!before.equals(after)) moved.incrementAndGet();
return null;
});
}
}
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("carriers used <= available processors: " + (carriers.size() <= cores));
System.out.println("some threads resumed on a different carrier: " + (moved.get() > 0));
}
}
Output:
state while sleeping: TIMED_WAITING
its stack, kept on the heap while unmounted:
at queryDatabase
at loadProfile
at handleRequest
at lambda$main$0
carriers used <= available processors: true
some threads resumed on a different carrier: true
The sleeping thread reports the normal TIMED_WAITING state, and its full call chain is intact even though no OS thread is executing it. The frames are data on the heap. In part 2, ten thousand threads shared at most one carrier per core, and some of them woke up on a different carrier from the one they started on. (The program reads the carrier's name from toString() only for this demonstration. Real code should never depend on it.)
The carrier is invisible
Mounting and unmounting are designed to be transparent:
Thread.currentThread()returns the virtual thread, never the carrier.- The carrier's
ThreadLocalvalues are invisible to the virtual thread, and the virtual thread's are invisible to the carrier. Each virtual thread has its own thread-locals. - Stack traces show the virtual thread's frames, not the carrier's scheduling code.
- There's no supported API that returns the carrier.
This is deliberate. Because a virtual thread can move to another carrier at every blocking call, any code that remembered "my" carrier would break. The JDK hides it so that the only thread your code ever sees is the virtual one.
An analogy: virtual memory
The name echoes virtual memory. A process sees a huge, private address space, but only the pages in use are in physical RAM. The rest are paged out to disk and paged back in when touched. Virtual threads work the same way with execution: a program sees as many threads as it wants, but only the ones running Java code occupy a carrier. The rest are "paged out" to the heap and paged back onto a carrier when they're ready to run.
What's current
- Java 24 (JEP 491) moved monitors (
synchronized,Object.wait) onto the unmount path, so most remaining causes of pinning are native code and class initializers. - Pollers are an internal detail and have been reworked between releases, for example to use virtual threads themselves on some platforms. Applications don't configure them.
- JDK Flight Recorder records mount-related events such as
jdk.VirtualThreadPinnedandjdk.VirtualThreadSubmitFailed(article 16).
Common questions
Is unmounting expensive? It costs about as much as copying a few stack frames: typically well under a microsecond for shallow stacks. That's far cheaper than an OS context switch, and it happens only when the thread would otherwise block for much longer.
Does a virtual thread really keep its whole stack while unmounted?
Yes. All frames, with their local variables, stay in heap stack chunks. That's why getStackTrace() works on an unmounted thread, and why a virtual thread with a very deep stack costs more memory than a shallow one.
What wakes up a virtual thread waiting for a socket? The JDK registered the socket with a poller when the thread blocked. When the OS reports that the socket is readable, the poller makes the virtual thread ready again, and the scheduler mounts it on a free carrier.
Why can't I get the carrier thread? A virtual thread has no permanent carrier. Exposing it would invite code that depends on it, such as storing data in the carrier's thread-locals, which would break as soon as the thread moved.
Summary
- A virtual thread's stack frames live in heap objects (stack chunks) that grow and shrink as needed.
- Mounting copies the top frames onto a carrier's native stack, and the code then runs at full speed.
- A blocking call freezes the frames to the heap, registers with a poller, timer or lock, and frees the carrier. When ready, the thread is thawed onto any free carrier.
- Socket I/O, sleep,
java.util.concurrentwaits and, since Java 24, monitors unmount. File I/O, native code and class initialization don't. - The carrier is invisible:
currentThread(), thread-locals and stack traces all refer to the virtual thread.
Practice questions
A virtual thread calls Thread.sleep(Duration.ofMinutes(5)). What resources does it hold during those five minutes?
Answer
Its heap objects (the Thread, its stack chunks with its frames and locals) and a scheduled timer entry. It holds no carrier and no OS thread. The carrier ran other virtual threads during the whole sleep.
Why does Thread.getStackTrace() work on a virtual thread that is currently unmounted?
Answer
Because its frames are stored as data in heap stack chunks while it's unmounted. The JDK can read them without the thread running. A blocked platform thread's frames, by contrast, are on its own native stack, which is still there because the OS thread is blocked rather than gone.
A developer stores a database connection in a ThreadLocal on a carrier thread, hoping all virtual threads on that carrier can share it. Will it work?
Answer
No. A virtual thread sees only its own thread-locals, never the carrier's, and it can move to a different carrier at any blocking call. Connections should come from a connection pool, not from thread-locals tied to a carrier.
Previous: Java Virtual Threads and Little's Law: Throughput, Scalability and When They Help
Next: Limiting Concurrency With Virtual Threads: Semaphores and Rate Limiting in Java

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.