Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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=true

Ten 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 finished

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.