Lesson · Virtual Threads & Structured Concurrency
Creating Virtual Threads: three entry points and one trap
12 min readCreating Virtual Threads
There are exactly three ways to start a virtual thread: Thread.startVirtualThread for a one-off, Thread.ofVirtual() builders when you want to name or delay one, and Executors.newVirtualThreadPerTaskExecutor() for the server shape. All three end in the same JVM scheduler. The one thing not to build is a pool of virtual threads, because a pool is a queue with a cap and both of those were the problem.
The question changed from how many to how
For thirty years, creating a thread was a decision about a scarce resource. You pooled them, sized them, warmed them, and handed them out carefully, because each one carried an OS thread and roughly a megabyte of stack.
Virtual threads remove the scarcity, and with it the sizing question. What is left is the shape question: one-off task, configured thread, or executor? Picking the wrong shape is now the most reliable way to get the old problems back, because a pool rebuilt on top of virtual threads brings the queue and the cap along with it.
This lesson walks the three entry points in the order you will meet them, then spends a section on the one pattern that must not survive the migration: pooling.
A virtual thread is created for a task and ends with it. There is nothing to configure for reuse, because there is no reuse.
Three ways in, one scheduler
All three entry points end in the same place: the JVM's virtual thread scheduler, which mounts threads on carriers as they become runnable. What differs is what you get back, and who owns the lifecycle.
Notice what is missing from the list: no constructors. new Thread(...) still creates a platform thread, and there is no public constructor for a virtual one. The factories below are the whole vocabulary.
| Entry point | Returns | Reach for it when |
|---|---|---|
Thread.startVirtualThread(task) | a started Thread | one task now, and you want to join or interrupt it |
Thread.ofVirtual().name(...).start(task) | a started, configured Thread | the name matters, or you want .unstarted for later |
Executors.newVirtualThreadPerTaskExecutor() | an ExecutorService | the server shape: many tasks, one virtual thread each |
Three doors, one scheduler: the choice is about configuration and lifecycle, never about pooling.
entry points · one destination
the APIs differ in configuration and lifecycle, not in where the thread runsThread.startVirtualThread(task)
returns a started Thread
one task now, and the caller may want to join or interrupt it
Thread.ofVirtual().name(..).start(task)
returns a started Thread
the name matters, or the thread should be unstarted for later
Executors.newVirtualThreadPerTaskExecutor()
returns an ExecutorService
many tasks, one virtual thread each: the server shape
JVM virtual thread scheduler
mounts runnable virtual threads on carriers; unmounted threads wait as heap data
carrier-1
one virtual thread mounted
carrier-2
one virtual thread mounted
parked virtual threads
stack chunks in the heap, no carrier held
Carriers default to the number of available processors and can be tuned with jdk.virtualThreadScheduler.parallelism. Nothing here is pooled: every task gets a thread, and every thread ends with its task.
One task now: startVirtualThread
Thread.startVirtualThread(task) creates a virtual thread, starts it, and hands back the Thread. It is the new Thread(task).start() of the virtual world, minus the OS bill.
The returned handle is a real Thread, so join(), interrupt(), getName() and isVirtual() all behave. That matters for scripts and handlers that need to wait for exactly one task.
One trap lives in this API, and it is a property of virtual threads rather than of the method: virtual threads are always daemon threads. If main returns while the task is still running, the JVM exits and the task dies mid-flight. The fix is one line: join it.
// Starts immediately and returns the running thread. Not joined, it can die // with the JVM: virtual threads are daemons, so main exiting kills them. Thread worker = Thread.startVirtualThread(() -> handle(request)); worker.join(); // wait here, or the task may not finish before main returns
startVirtualThread is for one task; the returned Thread is what keeps that task joinable.
Configure, name, then start
Thread.ofVirtual() returns a builder. Every property is settled before the thread exists: the name, and whether the thread starts now (.start(task)) or is created unstarted for later (.unstarted(task)).
Naming matters more here than it ever did for platform threads. Virtual threads are numerous, so the name is the only handle you will have when a thread dump or a log line needs to describe one. name(String) sets it directly; name(String prefix, long start) numbers them for you (worker-1, worker-2, and so on).
A builder is reusable, and it can also produce a ThreadFactory through .factory(). That factory creates virtual threads with the same settings, which is how virtual threads get into code that creates its own threads.
// The builder settles naming before the thread exists: a dump shows this name. Thread thread = Thread.ofVirtual() .name("order-" + order.id()) .start(() -> handle(order)); // One configured builder, many threads: numbers do the bookkeeping. ThreadFactory named = Thread.ofVirtual().name("request-", 1).factory();
Name virtual threads like you will have to find them later, because you will.
The server shape: a thread per task
Executors.newVirtualThreadPerTaskExecutor() is the entry point production code wants. Submit a task, get a fresh virtual thread for it: no pooling, no reuse, and no queue in front of the threads.
It still returns an ExecutorService, so the lifecycle is exactly what you already know: shutdown() when the application stops accepting work, and for a bounded program the try-with-resources form, whose close() shuts down and waits for the tasks to finish.
The executor itself holds no worker threads. It creates one virtual thread per task, and each thread ends when its task does. Because an object with no threads inside it is nearly free, even creating one of these per handled request is a shape the JDK's own examples use; most applications keep a single instance for the life of the process.
One task, one virtual thread: the executor is a shape, not a pool.
creation lab · how a virtual thread begins
// Creates a virtual thread, starts it, returns the Thread. Thread worker = Thread.startVirtualThread(() -> handle(request)); worker.join(); // or main may exit first: virtual threads are daemons
virtual threads
carriers · platform threads
carrier-1: vt-1 mounted
carrier-2: free
startVirtualThread creates one virtual thread and starts it immediately. It returns the Thread, which is the handle for join() and interrupt().
outcome · startVirtualThread
one task, one fresh thread, no pool
The handle is a real Thread: join(), interrupt() and isVirtual() all behave. Its only sharp edge is the daemon rule, and the JVM will not wait for it.
The pool you should not build
A pool exists to remove two costs: creating a thread, and reusing one. Neither cost survives the move to virtual threads. Creating one is cheap, and there is nothing to reuse, because a virtual thread is intended to run exactly one task and then end.
A pool adds back what the migration was meant to remove. Wrap a fixed pool of 200 around a virtual-thread factory and exactly 200 tasks run at a time while the rest queue in the executor, at which point the architecture is a platform pool with extra steps and none of the savings.
The same reasoning applies to the trick that usually rides along with pools: caching an expensive resource in a ThreadLocal so that pooled workers share it. With one thread per task, every task builds its own copy. If the goal is to limit or share something, do it to the resource itself, not to the threads.
| Pool thinking | Why it breaks here |
|---|---|
| Cap concurrency with N workers | the cap should describe the resource, not the thread count; limit the resource instead |
| Reuse expensive threads | a virtual thread is cheap to create and runs one task, so there is nothing to reuse |
| Pre-warm N threads | a per-task executor creates one only when a task arrives, and that is the point |
| Cache per-thread resources in a ThreadLocal | one thread per task turns the cache into a per-task allocation |
| Queue tasks in front of the workers | the queue was a symptom of the scarcity that virtual threads remove |
Do not pool what is cheap; bound what is scarce.
What to remember
The API fits in four lines:
- One-off tasks:
Thread.startVirtualThread(task), joined if the program is short-lived, because virtual threads are daemons. - Configured tasks:
Thread.ofVirtual().name(...).start(task), or.unstarted(task)to start later;.factory()plugs into executors and frameworks. - Server shape:
Executors.newVirtualThreadPerTaskExecutor(), closed withshutdown()or try-with-resources. - Never pooled: a pool of virtual threads is a queue with extra steps; bound the resource, not the thread count.
Pick the entry point by lifecycle, not by hesitation about creating a thread.
The task that vanished at exit
A demo starts a virtual thread, prints a counter, and finishes with an empty result. Nothing threw and nothing was cancelled: virtual threads are daemon threads, so once main returned the JVM exited and took the task with it. Platform threads hid this trap because the ones you created were usually not daemons and main waited for them. Every short-lived program that starts virtual threads must join them, or close the executor that owns them.
Interview angles
When would you use Thread.startVirtualThread instead of an executor?+
For a single task you want a handle on: it creates and starts the thread and returns it, so join and interrupt work directly. The per-task executor is the better shape once there are many tasks.
Common misconception: That startVirtualThread returns a Future. It returns the Thread itself.
Why is pooling virtual threads wrong?+
A pool shares expensive resources; a virtual thread is cheap and runs exactly one task. Pooling it adds a queue and a concurrency cap, which recreates the exact constraints the migration removed, and buys nothing in return.
If the pool was really there to limit something, express the limit where it belongs: a bounded connection pool, a semaphore around the scarce client, a rate limiter for a dependency.
What does Thread.ofVirtual().factory() give you?+
A ThreadFactory whose threads are virtual and inherit the builder's settings, including the name. It is the bridge for code you do not own, such as Executors.newThreadPerTaskExecutor(factory) or a framework that creates its own threads.
Do you still need shutdown() with a per-task executor?+
Yes. The executor owns a lifecycle, not a set of threads: shutdown is what tells it to stop accepting tasks, and close() (try-with-resources) shuts down and waits for the running ones.
The executor holds no worker threads between tasks, so there is nothing to warm up and nothing to drain beyond the tasks themselves.
How do you name virtual threads, and why bother?+
The builder takes name(String) or name(String prefix, long start) for numbered names. Naming is how a thread dump or a log line stays readable when there are thousands of threads.
The traditional dump was built for dozens or hundreds of platform threads and deliberately does not list virtual threads; the newer dump, for example jcmd <pid> Thread.dump_to_file, presents them alongside the platform threads. Names are what make that listing useful.
Follow-up: Where do virtual threads show up in a thread dump?