Continuations in Java: How Virtual Threads Pause and Resume
The mechanism under every virtual thread: a continuation runs code until it yields, then resumes from the same point with its stack intact. Experiments with the JDK's internal Continuation class, a generator, freeze and lazy thaw with return barriers, and Java 21 pinning.
kvi5hnuCode Sprout team member8 min readOn this page
Article 11 described what happens when a virtual thread blocks: its frames are copied to the heap, and later copied back onto some carrier. The object that does this is a continuation. It's the core of Project Loom, and every virtual thread is essentially a continuation plus a scheduler (article 23). This article looks at continuations directly.
What a continuation is
A continuation is a piece of code that can pause itself in the middle, at any depth of method calls, and later be resumed from exactly that point, with all its local variables and its call stack intact. Two operations define it:
run()starts the code, or resumes it from where it last paused.yield(), called from anywhere inside that code, pauses it. The pendingrun()returns to its caller.
This is a one-shot, delimited continuation in computer-science terms. "Delimited" means it captures only the frames between run() and yield(), not the whole program. "One-shot" means each pause can be resumed only once. The same idea powers generators in Python and JavaScript, coroutines in Kotlin, and async functions in many languages. Java's version has one notable difference: the code inside doesn't need to be written in any special way. No suspend or async keywords, no special return types. Any ordinary Java method can be paused.
The internal API
The JDK implements continuations in jdk.internal.vm.Continuation. It's internal: not exported, not documented, not supported, and free to change in any release. The JDK team decided to expose the idea only through virtual threads. To experiment with it, you have to export the package explicitly, at both compile time and run time:
javac --add-exports java.base/jdk.internal.vm=ALL-UNNAMED ContinuationDemo.java
java --add-exports java.base/jdk.internal.vm=ALL-UNNAMED ContinuationDemo
Never use this in application code. It's here only to see the mechanism.
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
import jdk.internal.vm.Continuation;
import jdk.internal.vm.ContinuationScope;
// Internal API: compile and run with --add-exports java.base/jdk.internal.vm=ALL-UNNAMED
public class ContinuationDemo {
static final ContinuationScope SCOPE = new ContinuationScope("demo");
/** A generator: the body "yields" values; next() resumes it until it produces the next one. */
static class Generator<T> implements Iterator<T> {
private final Continuation body;
private T next;
private boolean ready;
Generator(Consumer<Consumer<T>> producer) {
body = new Continuation(SCOPE, () -> producer.accept(value -> {
next = value;
ready = true;
Continuation.yield(SCOPE); // pause right after producing a value
}));
}
@Override public boolean hasNext() {
if (!ready && !body.isDone()) body.run(); // resume until the next value or the end
return ready;
}
@Override public T next() {
if (!hasNext()) throw new NoSuchElementException();
ready = false;
return next;
}
}
static void step(String name, int n) {
System.out.println(" " + name + ": step " + n);
}
public static void main(String[] args) {
// 1. A continuation runs until it yields; run() again resumes after the yield
Continuation booking = new Continuation(SCOPE, () -> {
step("booking", 1);
Continuation.yield(SCOPE);
step("booking", 2);
Continuation.yield(SCOPE);
step("booking", 3);
});
int calls = 0;
while (!booking.isDone()) {
System.out.println("run() call " + (++calls));
booking.run();
}
System.out.println("done after " + calls + " run() calls");
// 2. Local variables and the call stack survive the pause
Generator<String> fares = new Generator<>(emit -> {
int price = 200; // a local variable kept across yields
for (String city : new String[] {"Lisbon", "Porto", "Faro"}) {
emit.accept(city + " " + price);
price += 15;
}
});
StringBuilder out = new StringBuilder();
while (fares.hasNext()) out.append(fares.next()).append("; ");
System.out.println("generator produced: " + out);
// 3. Two continuations interleaved on one thread: a tiny scheduler
Continuation a = new Continuation(SCOPE, () -> { for (int i = 1; i <= 3; i++) { step("A", i); Continuation.yield(SCOPE); } });
Continuation b = new Continuation(SCOPE, () -> { for (int i = 1; i <= 3; i++) { step("B", i); Continuation.yield(SCOPE); } });
System.out.println("interleaving on thread " + Thread.currentThread().getName() + ":");
while (!a.isDone() || !b.isDone()) {
if (!a.isDone()) a.run();
if (!b.isDone()) b.run();
}
// 4. Yielding while holding a monitor
Object lock = new Object();
Continuation locked = new Continuation(SCOPE, () -> {
synchronized (lock) {
boolean yielded = Continuation.yield(SCOPE);
System.out.println("yield inside synchronized returned " + yielded);
}
});
try {
locked.run();
System.out.println("after first run: done=" + locked.isDone());
if (!locked.isDone()) locked.run();
} catch (Throwable t) {
System.out.println("yield inside synchronized: " + t);
}
}
}
Output on JDK 25:
run() call 1
booking: step 1
run() call 2
booking: step 2
run() call 3
booking: step 3
done after 3 run() calls
generator produced: Lisbon 200; Porto 215; Faro 230;
interleaving on thread main:
A: step 1
B: step 1
A: step 2
B: step 2
A: step 3
B: step 3
after first run: done=false
yield inside synchronized returned true
- Pause and resume. Each
run()executed the code up to the nextyield, and the nextrun()continued right after it. The continuation was done after the third call. - State survives. The generator's loop variable
city, its localprice, and the whole call chain from the lambda throughproducer.acceptdown to the inner consumer were all kept while paused.yieldwas called two levels deep inside other methods, and that works fine. - Interleaving. Two continuations took turns on a single thread,
main. That's a scheduler in four lines. Replace "take turns" with "aForkJoinPoolruns whichever is ready" and "yield" with "park when blocked", and you have virtual threads. - Monitors. On JDK 25, the continuation could yield while holding a monitor. Running the same file on Java 21 prints
yield inside synchronized: java.lang.IllegalStateException: Pinned: MONITORfor the last part instead: the continuation refused to yield because a monitor was held. That's exactly thesynchronizedpinning of Java 21–23 (article 13), seen from below. JEP 491 in Java 24 removed it.
How freeze and thaw work
A continuation's frames live on the thread's stack while it runs, because that's where the CPU executes code. When it yields, the JVM freezes it: it copies the frames between run() and yield() into a stack chunk object on the heap, and run() returns. When resumed, the JVM thaws it: it copies frames back onto the current thread's stack (which may be a different thread) and returns from yield().

Copying a deep stack on every pause and resume would be slow. Two optimizations keep it cheap:
- Lazy thaw. On resume, a small stack may be copied back whole, but for a deep stack the JVM copies only the top frame or two. Below them it places a return barrier: a small stub that runs when the thawed frame returns. The barrier thaws the next frame from the heap chunk, and so on. Code that yields again before returning very far never pays for the frames below.
- Incremental freeze. Frames that were never thawed are still in the heap chunk, so the next freeze copies only the frames that actually changed.
The copying is a memory move of compiled frames, not a re-execution. Mounted code runs at full JIT-compiled speed. This is why virtual threads handle deep framework stacks well: a typical yield-and-resume touches only a small part of the stack.
The JVM also has to handle frames it can't move. Native frames can't be copied, and the JVM must keep certain frames in place during class initialization. When such a frame sits between run() and yield(), the continuation is pinned: yield fails, and the virtual-thread code falls back to blocking the carrier (article 14). The Pinned: MONITOR message above names the reason, and JFR's pinnedReason field reports the same information (article 16).
Continuations and virtual threads
A virtual thread adds three things to a continuation:
| Continuation (internal) | Virtual thread (public) |
|---|---|
run() | the scheduler mounts the thread on a carrier and runs its continuation |
Continuation.yield(scope) | called inside LockSupport.park() whenever a virtual thread blocks |
whoever calls run() next | the poller, timer or unpark that resubmits the thread to the scheduler |
| no identity | a real Thread object: name, ID, interrupt status, thread-locals |
The scope argument lets a continuation say which enclosing continuation should pause. The JDK uses its own scope for virtual threads, so your code can't accidentally yield one.
What's current
jdk.internal.vm.Continuationremains internal through Java 27, and there are no plans to make it public. The supported way to use continuations is virtual threads.- Since Java 24, continuations can yield while holding monitors. Native frames and some class-initialization frames still prevent a yield.
- The freeze and thaw code is part of HotSpot. Its details, such as stack chunk layout and barrier placement, change between releases without affecting Java code.
Common questions
Why doesn't Java make Continuation public?
Because direct use is easy to get wrong (for example, yielding while holding a lock, or resuming from the wrong thread), and because virtual threads already cover the main use case. Keeping it internal lets the JDK change it freely. Generators and coroutines can be built on virtual threads and queues instead.
Is a continuation a thread?
No. It's just resumable code. It runs on whichever thread calls run(), and it can run on different threads at different times, which is exactly what lets a virtual thread move between carriers.
What does "one-shot" mean in practice? Each pause can be resumed once, and the continuation can't be copied to resume the same point twice. That's enough for threads and generators, and much cheaper than multi-shot continuations, which would have to copy the stack on every resume.
Do continuations make my code slower while running? No. While mounted, the code is ordinary compiled code on a native stack. The cost is only at yield and resume, which copy a few frames.
Summary
- A continuation is code that can pause itself at any call depth with
yieldand later resume from the same point withrun(), keeping its locals and call stack. - The JDK's
jdk.internal.vm.Continuationis internal and needs--add-exportsfor experiments. Production code uses virtual threads instead. - Freeze copies the continuation's frames into a heap stack chunk. Thaw copies deep stacks back lazily, a frame or two at a time, using return barriers.
- Frames the JVM can't move (native code, class initialization, and monitors before Java 24) pin the continuation, and yield fails.
- A virtual thread is a continuation plus a scheduler, a wake-up mechanism and a
Threadidentity.
Practice questions
In the booking example, why did the loop call run() three times, not two?
Answer
There are two yield calls, which split the body into three parts. Each run() executes one part: up to the first yield, then up to the second, then to the end. Only after the third run() does isDone() become true.
A continuation's body calls a native method, and that native code calls back into Java, which calls Continuation.yield. What happens, and what does it correspond to for virtual threads?
Answer
The yield fails because a native frame sits between run() and yield(): the JVM can't copy it to the heap. The continuation is pinned. For a virtual thread, that means a blocking call made from such a callback can't unmount and holds the carrier instead (article 14).
Why does lazy thaw make deep call stacks cheap for virtual threads?
Answer
On resume, only the top frame or two are copied back. The rest stay in the heap chunk behind a return barrier until the code actually returns into them. A thread that blocks repeatedly near the top of a 200-frame stack only copies a few frames each time.
Previous: The Virtual Thread Scheduler: How ForkJoinPool Runs Java Virtual Threads
Next: Building Virtual Threads From Scratch in Java With Continuations

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.