Building Virtual Threads From Scratch in Java With Continuations
A toy version of virtual threads in about 60 lines: a continuation per micro thread, a FIFO ForkJoinPool of carriers, a timer for sleep, and the yield-then-reschedule order that avoids a classic race. 10,000 micro threads on 2 carriers, and why real blocking calls had to be rewritten.
kvi5hnuCode Sprout team member7 min readOn this page
Article 24 showed continuations pausing and resuming on one thread. Article 23 showed the scheduler that runs virtual threads and the helpers that wake them up. This article joins the two into a working toy: micro threads, each a continuation scheduled on a small ForkJoinPool, with a sleep that gives the carrier back. Building it makes clear what the JDK's virtual threads actually have to do, and where the hard parts are.
Like article 24, this code uses the internal jdk.internal.vm.Continuation class. It's for understanding only. Compile and run with --add-exports java.base/jdk.internal.vm=ALL-UNNAMED.
The design
A micro thread needs:
- A continuation wrapping its task, so it can pause in the middle.
- A scheduler: a
ForkJoinPoolin asyncMode (FIFO), as in the JDK. Its workers are the carriers. "Scheduling" a micro thread means submitting a task that mounts it and callscontinuation.run(). - A way to wait without a carrier: here,
MicroThread.sleep(ms)yields the continuation and asks a timer to resubmit it later. - A "current thread": a thread-local on the carrier telling code which micro thread is running, so
sleepknows whom to pause.

The race that must be avoided
The obvious way to write sleep is: schedule a timer task that will resubmit me, then yield. That has a race. If the delay is short or the carrier is slow, the timer can fire and another carrier can call continuation.run() before the first carrier has finished yielding. Two threads would then run the same continuation at once, which corrupts it or throws IllegalStateException.
The fix is to make the order explicit: sleep only records what it wants, then yields. After continuation.run() has returned on the carrier (so the micro thread is fully unmounted), the carrier arms the timer. The JDK solves the same problem with a small state machine: LockSupport.park moves a virtual thread from RUNNING to PARKING, yields, and then an afterYield() step on the carrier moves it to PARKED. If an unpark arrived in between, the state shows it and the thread is resubmitted immediately.
The code
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
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 MicroThreads {
/** A toy "virtual thread": a continuation plus a scheduler and a timer. */
static final class MicroThread {
private static final ContinuationScope SCOPE = new ContinuationScope("micro");
private static final ForkJoinPool CARRIERS = new ForkJoinPool(2,
ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); // FIFO, like the real one
private static final ScheduledExecutorService TIMER = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "micro-timer");
t.setDaemon(true);
return t;
});
private static final ThreadLocal<MicroThread> CURRENT = new ThreadLocal<>();
private static final AtomicInteger IDS = new AtomicInteger();
final int id = IDS.incrementAndGet();
private final Continuation continuation;
private long sleepMillis = -1; // set by sleep(), read after the yield
private MicroThread(Runnable task) {
continuation = new Continuation(SCOPE, task);
}
static MicroThread start(Runnable task) {
MicroThread t = new MicroThread(task);
t.submit();
return t;
}
static MicroThread current() { return CURRENT.get(); }
/** Like Thread.sleep on a virtual thread: give the carrier back, come back later. */
static void sleep(long millis) {
MicroThread self = current();
self.sleepMillis = millis;
Continuation.yield(SCOPE); // unmount: run() on the carrier returns
}
private void submit() { CARRIERS.execute(this::mountAndRun); }
/** What a carrier does: mount, run until yield or end, then handle the yield. */
private void mountAndRun() {
CURRENT.set(this);
try {
continuation.run(); // runs until the next yield, or to the end
} finally {
CURRENT.remove();
}
// Only now, with the continuation fully unmounted, arrange for it to be resumed.
// Scheduling the wake-up before yielding would race: the timer could resubmit it while it's still mounted.
if (!continuation.isDone() && sleepMillis >= 0) {
long delay = sleepMillis;
sleepMillis = -1;
TIMER.schedule(this::submit, delay, TimeUnit.MILLISECONDS);
}
}
static String carrierName() { return Thread.currentThread().getName(); }
}
public static void main(String[] args) throws InterruptedException {
// 1. One micro thread, watched closely
CountDownLatch first = new CountDownLatch(1);
MicroThread.start(() -> {
MicroThread me = MicroThread.current();
System.out.println("micro-" + me.id + " started on " + MicroThread.carrierName());
MicroThread.sleep(100);
System.out.println("micro-" + me.id + " resumed after sleep (same object: " + (MicroThread.current() == me) + ")");
first.countDown();
});
first.await();
// 2. 10,000 micro threads, each sleeping twice for 100 ms, on just 2 carriers
int count = 10_000;
CountDownLatch done = new CountDownLatch(count);
Set<String> carriers = ConcurrentHashMap.newKeySet();
AtomicInteger moved = new AtomicInteger();
long start = System.nanoTime();
for (int i = 0; i < count; i++) {
MicroThread.start(() -> {
String before = MicroThread.carrierName();
MicroThread.sleep(100);
MicroThread.sleep(100);
String after = MicroThread.carrierName();
carriers.add(before);
carriers.add(after);
if (!before.equals(after)) moved.incrementAndGet();
done.countDown();
});
}
done.await();
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(count + " micro threads finished in about " + Math.round(ms / 100.0) * 100
+ " ms on " + carriers.size() + " carriers; some resumed on another carrier: " + (moved.get() > 0));
// 3. The same idea fails if the code blocks in a way our scheduler doesn't know about
CountDownLatch blocking = new CountDownLatch(10);
start = System.nanoTime();
for (int i = 0; i < 10; i++) {
MicroThread.start(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
blocking.countDown(); // a real sleep: blocks the carrier, no yield
});
}
blocking.await();
ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("10 micro threads calling Thread.sleep(100) took about " + Math.round(ms / 100.0) * 100
+ " ms: the carriers were blocked, not freed");
}
}
Output on JDK 25 (times rounded, may differ slightly):
micro-1 started on ForkJoinPool-1-worker-1
micro-1 resumed after sleep (same object: true)
10000 micro threads finished in about 200 ms on 2 carriers; some resumed on another carrier: true
10 micro threads calling Thread.sleep(100) took about 500 ms: the carriers were blocked, not freed
What it shows
- Identity survives the pause. The micro thread resumed after its sleep with the same object as "current", even though the carrier that resumed it may be a different one. The carrier's thread-local is set on each mount and cleared on each unmount, the same idea the JDK uses to make
Thread.currentThread()return the virtual thread. - Waiting costs no carrier. 10,000 micro threads each slept twice for 100 ms, and the whole batch finished in about 200 ms using two carriers. While sleeping, a micro thread is just a continuation object on the heap and a timer entry. Many resumed on a different carrier from the one they started on.
- Unknown blocking breaks it. Ten micro threads that called the real
Thread.sleeptook about 500 ms: two carriers, five rounds of 100 ms. Our scheduler knows nothing aboutThread.sleep, so the carrier simply blocked. This is the problem the JDK solved by rewriting every blocking point: sockets, locks, queues,sleep,joinand monitors all detect a virtual thread and yield instead. A virtual-thread implementation is only as good as its coverage of blocking calls.
What the real implementation adds
The toy is about 60 lines. java.lang.VirtualThread and its helpers are several thousand, because they also handle:
- A real
Thread: names, IDs, interrupts (an interrupt must wake a parked virtual thread), thread-locals, uncaught-exception handlers,join. - A complete park/unpark protocol: every JDK blocking point uses
LockSupport.park, with a state machine that handles races between parking, unparking, interrupts and timeouts. - I/O integration: pollers for sockets (article 23), and compensation for operations that must block the carrier.
- Pinning: detecting when a continuation can't yield (native frames, class initialization) and parking the carrier instead.
- Observability: JFR events, thread dumps that include virtual threads, and debugger support.
- Correctness under the memory model: mounting and unmounting are synchronization points, so a virtual thread sees its own writes after moving carriers.
What's current
java.lang.VirtualThread(Java 21+) follows this design: a continuation, a scheduler (aForkJoinPoolin asyncMode) and wake-ups from pollers, timers andunpark.- The continuation API stays internal through Java 27, so libraries can't build their own scheduler on it in supported code.
- Since Java 24, monitors are part of the park/yield protocol, which removed the most common source of pinning.
Common questions
Could a library build its own virtual threads like this?
Not in a supported way. It would need the internal Continuation class, and, more importantly, every blocking call in the JDK and in libraries would have to know about its scheduler. That's why the feature lives inside the JDK.
Why does the toy use a ForkJoinPool instead of a fixed thread pool?
It would work with any executor. A ForkJoinPool in asyncMode mirrors the real scheduler: per-worker FIFO queues and work stealing, which matter when hundreds of thousands of micro threads become ready at once.
Why is sleepMillis not volatile?
It's written by the micro thread and read by the same carrier right after continuation.run() returns, in the same thread. The later resubmission goes through the timer's and pool's queues, which provide the necessary happens-before ordering. A real implementation documents these guarantees carefully.
What would MicroThread.sleep do if called from an ordinary thread?
current() would return null, and the code would throw a NullPointerException. The JDK's Thread.sleep checks whether the caller is virtual and only yields in that case.
Summary
- A virtual thread is, at heart, a continuation submitted to a scheduler, with a way to be resubmitted when what it waits for happens.
- Waiting means: record the wake-up condition, yield, and let the carrier arm the timer or registration only after the yield has completed, to avoid two carriers running one continuation.
- 10,000 toy micro threads slept concurrently on two carriers, but a single real blocking call they didn't know about blocked a carrier.
- The JDK's work is mostly in integration: rewriting blocking calls, interrupts, pinning, I/O pollers and observability.
Practice questions
In MicroThreads, what could go wrong if sleep scheduled the timer task itself, before calling Continuation.yield?
Answer
The timer could fire and submit the micro thread to the pool before the yield had completed. Another carrier would then call continuation.run() while the first carrier was still running it, so two threads would run one continuation at once. That's illegal (the JDK throws IllegalStateException) and would corrupt the stack. Arming the timer after run() returns avoids the race.
10,000 micro threads finished two 100 ms sleeps in about 200 ms on two carriers. Using Little's Law, roughly how many could be in progress at the same time?
Answer
All 10,000: each spends about 200 ms in the system, and 10,000 finish in about 200 ms, so N = λ × d = (10,000 / 0.2 s) × 0.2 s = 10,000. Almost all of that time is spent sleeping, which doesn't hold a carrier, so two carriers are enough.
Why did the third part of the demo take about 500 ms?
Answer
Those micro threads called the real Thread.sleep, which blocks the carrier thread because our scheduler isn't integrated with it. Two carriers ran ten 100 ms sleeps two at a time: five rounds, about 500 ms. The JDK avoids this by making Thread.sleep (and every other blocking call) yield when called from a virtual thread.
Review quiz
Test yourself on Part 3 with the Part 3 review quiz: The Mechanics Behind Java Virtual Threads. It covers thread pools from scratch, ThreadPoolExecutor's decision order and policies, Callable and Future, fork/join and work stealing, the virtual-thread scheduler and pollers, and continuations.
Previous: Continuations in Java: How Virtual Threads Pause and Resume
Next: The Problems With Unstructured Concurrency in Java: Leaks, Lost Errors and Orphaned Tasks

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.