Virtual threads and structured concurrency question 123 of 180 mid
What does Executors.newVirtualThreadPerTaskExecutor().close() do?
- Nothing, it is a no-op
- Correct: It blocks until every submitted task has finished, which is why it is used with try-with-resources as a join point
- It interrupts running tasks
- It rejects the tasks still queued
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.
Quiz yourself on Virtual threads and structured concurrency Suggest a correction