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.
Code
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
HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.