Thread.ofVirtual()
Creates a virtual thread — a lightweight thread you can start by the million.
Available since: Java 21
Syntax
public static Thread.Builder.OfVirtual ofVirtual()
public static Thread startVirtualThread(Runnable task)Return value
Thread.Builder.OfVirtualA builder of virtual threads.
Examples
Starting a virtual thread:
void main() throws InterruptedException {
Thread t = Thread.ofVirtual().name("worker").start(() ->
IO.println(Thread.currentThread().getName() + " virtual=" + Thread.currentThread().isVirtual()));
t.join();
}Output:
worker virtual=trueTen thousand threads, each sleeping 100 ms:
void main() throws InterruptedException {
var done = new AtomicInteger();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10_000; i++) {
threads.add(Thread.startVirtualThread(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) { return; }
done.incrementAndGet();
}));
}
for (Thread t : threads) t.join();
IO.println(done.get() + " tasks finished");
}Output:
10000 tasks finishedNotes
Virtual threads are managed by the JVM rather than the operating system: while a thread waits (sleep, network, file) it does not occupy an OS thread. They suit many waiting tasks but do not speed up computation. They need no pools — create a new thread per task, usually with Executors.newVirtualThreadPerTaskExecutor().
See also
- Executors.newVirtualThreadPerTaskExecutor() — Creates a service that runs every task in its own virtual thread.
- Thread — A thread of execution that lets a program do several things at once.
- Thread.start() — Starts a thread: its code begins running in parallel with the caller.
Related recipes
In the tutorial
- Virtual threads — Virtual threads in Java 21+ — how they differ from ordinary threads, Thread.ofVirtual, newVirtualThreadPerTaskExecutor, thousands of tasks at once and limiting with a Semaphore.