Virtual threads and structured concurrency question 117 of 180 mid
What problem does structured concurrency solve?
- It makes tasks run in order
- Correct: It gives concurrent subtasks a scope with a defined lifetime, so errors propagate, cancellation is automatic and nothing outlives the block that started it
- It replaces all executors
- It removes the need for exception handling
With an executor, a submitted task's lifetime is unrelated to the code that submitted it. If the caller
returns early or fails, the subtasks keep running, and cancelling them is manual bookkeeping everyone
gets wrong. Errors surface only when someone calls get().
Structured concurrency binds the subtasks to a lexical scope, the same way a block binds local variables. The scope does not exit until every fork has finished or been cancelled, a failure in one fork cancels the siblings, and the subtask's stack trace is linked to the parent's, so thread dumps show the tree.
try (var scope = StructuredTaskScope.open()) { // JDK 25 API shape
var user = scope.fork(() -> loadUser(id));
var order = scope.fork(() -> loadOrders(id));
scope.join();
return new Page(user.get(), order.get());
} // on any exit path, both forks are finished or cancelled
The API is still evolving (incubating in JDK 19 and 20, a preview from JDK 21, and still a preview in the factory-based shape of JDK 25), so name the concept confidently and the exact signature with a caveat.
Quiz yourself on Virtual threads and structured concurrency Suggest a correction