Java / Java 21 Virtual Threads Interview questions
How do you use Executors.newVirtualThreadPerTaskExecutor()?
This factory method returns an ExecutorService that starts a brand-new virtual thread for every task you submit - there's no pooling and no queue limit, since virtual threads are cheap enough to create on demand.
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 10_000; i++) { int id = i; executor.submit(() -> handleRequest(id)); } } // try-with-resources calls shutdown() and awaits completion
Using it in a try-with-resources block is the recommended pattern: it automatically shuts down the executor and waits for in-flight tasks to finish once the block exits.
More Related questions...