Virtual Threads Per Request Executor

Fan out thousands of blocking tasks onto Java 21 virtual threads with Executors.newVirtualThreadPerTaskExecutor and time the run against the platform pool.

JavaResilience

Code

snippet
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class VirtualThreadFanout {

    public static void main(String[] args) throws Exception {
        int taskCount = 10_000;
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            long start = System.nanoTime();
            for (int i = 0; i < taskCount; i++) {
                int taskId = i;
                executor.submit(() -> {
                    // 阻塞调用在虚拟线程上代价极低:挂起而非占用 OS 线程
                    Thread.sleep(Duration.ofMillis(50));
                    return "task-" + taskId;
                });
            }
            executor.close();
            long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
            System.out.printf("%d tasks on virtual threads in %d ms%n", taskCount, elapsedMs);
        }

        Thread.startVirtualThread(() -> System.out.println("named: " + Thread.currentThread()));
    }
}

How the snippet works

Virtual Threads Per Request Executor comes down to the class VirtualThreadFanout.

Repetition is confined to for (int i = 0; i < taskCount; i++) — the rest of the file is straight-line. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Applying it

The demo output is labeled (named:), so every printed line maps back to its originating operation.

Statements that matter

Thread.sleep(Duration.ofMillis(50));
return "task-" + taskId;

Interactive Tools for This Topic

FAQ

What does Virtual Threads Per Request Executor print when run?
Invoke the file as-is — the `named:` prefixes identify which step printed each line.