Creating Java Virtual Threads: startVirtualThread, Thread.Builder, Factories and Executors
Every way to create and run Java virtual threads: Thread.startVirtualThread, Thread.ofVirtual builders, ThreadFactory, newVirtualThreadPerTaskExecutor and newThreadPerTaskExecutor. Plus interruption, cheap blocking Future.get, invokeAll, and setting up a JDK for virtual threads.
kvi5hnuCode Sprout team member7 min readOn this page
Virtual threads don't need a new API. They use java.lang.Thread and ExecutorService, the types Java developers already know, plus a few factory methods added in Java 21. This article shows each way to create them, when to use which, and how familiar operations such as interruption and Future.get() behave.
Setting up a JDK
Virtual threads need Java 21 or later. Any distribution works: Oracle JDK, Eclipse Temurin, Amazon Corretto, Azul Zulu, Microsoft Build of OpenJDK and others. For new projects, pick the current long-term-support release, Java 25: it includes the Java 24 fix for synchronized pinning (article 13) and final scoped values (Part 5).
A version manager makes it easy to keep several JDKs side by side. On macOS and Linux, SDKMAN is popular:
sdk list java # show available distributions and versions
sdk install java 25.0.x-tem # install Temurin 25: pick the latest 25 identifier from the list
sdk use java 25.0.x-tem # use it in the current shell
java -version
Structured concurrency is still a preview API in Java 25 to 27, so the examples in Part 4 also need the --enable-preview flag. Everything in this article is final and needs no flags.
Five ways to create virtual threads
| API | Returns | Use it for |
|---|---|---|
Thread.startVirtualThread(runnable) | a started Thread | quick one-off tasks |
Thread.ofVirtual()...start(runnable) | a started Thread | tasks that need a name or other settings |
Thread.ofVirtual()...unstarted(runnable) | a NEW thread | creating now, starting later |
Thread.ofVirtual()...factory() | a ThreadFactory | handing virtual threads to code that takes a factory |
Executors.newVirtualThreadPerTaskExecutor() | an ExecutorService | existing executor-based code, Future results, invokeAll |
Executors.newThreadPerTaskExecutor(factory) is a sixth variant: a thread-per-task executor that uses your factory, so all its threads get your names and settings.
The builder methods are the ones you'll use most:
| Builder method | Effect |
|---|---|
name(String) | every thread gets this name |
name(String prefix, long start) | names prefix + start, prefix + (start + 1), … |
uncaughtExceptionHandler(handler) | handler for exceptions that escape run |
inheritInheritableThreadLocals(boolean) | whether to copy the creator's InheritableThreadLocal values (default true) |
A builder is mutable and not thread-safe, but the factory it produces is thread-safe: create the factory once and share it.
Trying them all
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
public class Solution {
public static void main(String[] args) throws Exception {
// 1. The shortest form
Thread a = Thread.startVirtualThread(() -> System.out.println("1. startVirtualThread"));
a.join();
// 2. A builder: configure, then start (or create unstarted)
Thread b = Thread.ofVirtual().name("loader").unstarted(() ->
System.out.println("2. builder, name=" + Thread.currentThread().getName()));
b.start();
b.join();
// 3. A factory from a builder: names with a counter, shared handler
ThreadFactory factory = Thread.ofVirtual()
.name("fetch-", 1)
.uncaughtExceptionHandler((t, e) -> System.out.println(" " + t.getName() + " failed: " + e.getMessage()))
.factory();
Thread c = factory.newThread(() -> { throw new IllegalStateException("no route"); });
c.start();
c.join();
System.out.println("3. factory made " + c.getName());
// 4. An executor that starts a new virtual thread per task, named by our factory
try (ExecutorService executor = Executors.newThreadPerTaskExecutor(factory)) {
List<Callable<String>> lookups = List.of(
() -> lookup("flight", 120),
() -> lookup("hotel", 80),
() -> lookup("weather", 40));
List<Future<String>> results = executor.invokeAll(lookups); // waits for all, keeps order
for (Future<String> f : results) System.out.println("4. " + f.get());
}
// 5. Interruption works exactly as with platform threads
interruptDemo(Thread.ofPlatform());
interruptDemo(Thread.ofVirtual());
}
static String lookup(String what, long millis) throws InterruptedException {
Thread.sleep(millis); // a blocking call: unmounts the virtual thread
return what + " on " + Thread.currentThread().getName().replaceAll("\\d+$", "N")
+ " (virtual=" + Thread.currentThread().isVirtual() + ")";
}
static void interruptDemo(Thread.Builder builder) throws InterruptedException {
CountDownLatch twoSteps = new CountDownLatch(2);
Thread worker = builder.start(() -> {
String kind = Thread.currentThread().isVirtual() ? "virtual" : "platform";
try {
for (int step = 1; step <= 5; step++) {
System.out.println("5. " + kind + " step " + step);
twoSteps.countDown();
Thread.sleep(200);
}
} catch (InterruptedException e) {
System.out.println("5. " + kind + " interrupted while sleeping");
}
});
twoSteps.await();
worker.interrupt();
worker.join();
}
}
Output:
1. startVirtualThread
2. builder, name=loader
fetch-1 failed: no route
3. factory made fetch-1
4. flight on fetch-N (virtual=true)
4. hotel on fetch-N (virtual=true)
4. weather on fetch-N (virtual=true)
5. platform step 1
5. platform step 2
5. platform interrupted while sleeping
5. virtual step 1
5. virtual step 2
5. virtual interrupted while sleeping
Things to notice:
- Every example joins or closes. Virtual threads are daemon threads. Without
join()or the executor'sclose(),maincould return and the JVM would exit before the work ran. - The factory's counter is shared. Thread
cbecamefetch-1, and the three executor tasks got the next numbers. The output replaces those numbers withN, because which lookup gets which number depends on timing. invokeAllkeeps the order. The results come back in the order of the task list, not the order in which the tasks finished (here, weather finished first).Thread.Builderis a common type.interruptDemotakes aThread.Builder, so the same code runs on a platform or a virtual thread. That's a handy way to compare behavior or let configuration decide.
Interruption is unchanged
Cancelling a virtual thread works the same way as cancelling a platform thread: call interrupt(), and the thread either sees InterruptedException from a blocking call or checks isInterrupted() itself. The demo's last six lines show identical behavior for both kinds. The one difference is invisible: while the virtual thread sleeps, it's unmounted, so it isn't holding a carrier.
The usual rules from article 2 apply: don't swallow InterruptedException, and restore the flag if you can't rethrow it.
Blocking on Future.get() is cheap now
With platform threads, future.get() was something to avoid: the calling thread sat idle, holding an OS thread, until the result arrived. On a virtual thread, get() unmounts the caller while it waits. That changes how you write aggregation code. The simplest version is fine:
String describeTrip(long id) throws InterruptedException, ExecutionException {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> weather = executor.submit(() -> forecast(id));
Future<String> events = executor.submit(() -> localEvents(id));
return weather.get() + ", " + events.get(); // both calls run concurrently
}
}
There are no callbacks or composition operators: submit the calls, then block on the results. For a list of similar tasks, invokeAll submits them all and returns their futures in order, as the demo showed.
This code still has the gaps from article 4: if forecast fails, localEvents keeps running until close() waits for it, and nothing sets a deadline. get(timeout, unit) helps with the deadline but not with cancelling the siblings. That's what structured concurrency is for:
try (var scope = StructuredTaskScope.open()) { // default policy: all must succeed
Subtask<String> weather = scope.fork(() -> forecast(id));
Subtask<String> events = scope.fork(() -> localEvents(id));
scope.join(); // if one fails, the other is cancelled
return weather.get() + ", " + events.get();
}
When a subtask fails, the scope cancels (interrupts) the others, and join() throws. Part 4 covers the API in full, including timeouts and how its exceptions changed between Java 25 and Java 27.
Which one should I use?
- In application code that fans out, use
Executors.newVirtualThreadPerTaskExecutor()in a try-with-resources block, so the block can't finish while its tasks are running. On Java 28 and later, preferStructuredTaskScope. - When an API wants a
ThreadFactory, such as a framework, an HTTP server ornewThreadPerTaskExecutor, passThread.ofVirtual().name("...", 0).factory(). - For a single background task that needs a name, use
Thread.ofVirtual().name(...).start(...)and keep the returnedThreadso you can join it. - Use
Thread.startVirtualThreadfor demos and throwaway tasks.
Don't put virtual threads in a fixed-size pool, for example with Executors.newFixedThreadPool(n, virtualFactory). It works, but it reintroduces the cap and the queueing that virtual threads were meant to remove. If the reason is limiting concurrent access to a resource, use a semaphore instead (article 12).
What's current
Thread.ofVirtual(),Thread.startVirtualThread(),Executors.newVirtualThreadPerTaskExecutor()andExecutors.newThreadPerTaskExecutor(ThreadFactory)are final since Java 21 and unchanged through Java 27.StructuredTaskScopeis in its fifth (Java 25), sixth (Java 26) and seventh (Java 27) preview. It becomes final in Java 28 with the Java 27 API.
Common questions
Is Executors.newVirtualThreadPerTaskExecutor() a thread pool?
No. It creates a new virtual thread for every task and never reuses them. It has no queue and no size limit. Closing it waits for the tasks that were submitted.
Should I name virtual threads?
Name them when it helps diagnostics, for example order- plus a counter for request handlers. Virtual threads are unnamed by default (their name is the empty string), and a thread dump with 50,000 unnamed threads is hard to read. Names cost little.
What does inheritInheritableThreadLocals(false) do?
It stops the new thread from copying the creator's InheritableThreadLocal values. With millions of short-lived threads, copying large inherited maps can be a real cost. Article 15 covers thread-locals and virtual threads.
Can I create a virtual thread with new Thread(...)?
No. Every Thread constructor creates a platform thread. Virtual threads come only from Thread.ofVirtual(), Thread.startVirtualThread(), or an executor or factory built on them.
Summary
- Create virtual threads with
Thread.startVirtualThread, theThread.ofVirtual()builder (start,unstarted,factory), or a thread-per-task executor. - Builders set names (optionally with a counter), an uncaught exception handler and thread-local inheritance. Factories made from them are thread-safe.
- Always join virtual threads or close their executor, because they're daemon threads.
- Interruption works exactly as for platform threads.
- Blocking in
Future.get()orinvokeAllis cheap on a virtual thread, so simple aggregation code scales. Structured concurrency adds cancellation and error handling. - Don't pool virtual threads. Limit access to scarce resources with a semaphore.
Practice questions
What names do the three threads get?
var builder = Thread.ofVirtual().name("job-", 10);
Thread a = builder.start(() -> {});
Thread b = builder.start(() -> {});
Thread c = Thread.ofVirtual().name("job-", 10).start(() -> {});
Answer
job-10, job-11 and job-10. Each builder has its own counter, which increases each time it creates a thread. Thread c comes from a new builder, so its counter starts at 10 again.
Why is this a poor design, and what should replace it?
ExecutorService pool = Executors.newFixedThreadPool(50, Thread.ofVirtual().factory());
Answer
It runs tasks on virtual threads but caps concurrency at 50 and queues the rest, so the benefits of virtual threads (one cheap thread per task, no queueing) are lost. If the goal is to protect a resource that tolerates only 50 concurrent calls, use Executors.newVirtualThreadPerTaskExecutor() and guard the resource with a Semaphore of 50 permits.
A virtual thread is sleeping in Thread.sleep(Duration.ofSeconds(30)). Another thread calls interrupt() on it. What happens?
Answer
The sleep ends immediately with an InterruptedException, and the interrupt flag is cleared, exactly as with a platform thread. While it slept, the virtual thread was unmounted and wasn't using a carrier.
Previous: What Is a Java Virtual Thread? Platform Threads, Virtual Threads and How They Differ
Next: Java Virtual Threads and Little's Law: Throughput, Scalability and When They Help

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.