Java Concurrency Interview

Virtual threads and structured concurrency question 123 of 180 mid

What does Executors.newVirtualThreadPerTaskExecutor().close() do?

ExecutorService extends AutoCloseable since Java 19, and close() means shutdown plus awaitTermination, retrying on interrupt. With try-with-resources that gives you a scope whose closing brace is a guaranteed join:

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    results = urls.stream().map(url -> executor.submit(() -> fetch(url))).toList();
}   // every fetch has completed here

This is structured concurrency's shape without its error propagation: a failure in one task does not cancel the others, and you still collect outcomes from the futures yourself. It is the pragmatic halfway house available today in stable API.

virtual-threads executors

Quiz yourself on Virtual threads and structured concurrency Suggest a correction