Java / Java 21 Virtual Threads Interview questions
How does StructuredTaskScope manage a group of virtual threads?
StructuredTaskScope lets you fork several subtasks, each running on its own virtual thread, and treat them as one unit bound to the enclosing block's lifetime.
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { Subtask<String> user = scope.fork(() -> fetchUser()); Subtask<String> order = scope.fork(() -> fetchOrder()); scope.join(); // wait for both, or first failure scope.throwIfFailed(); // propagate any failure combine(user.get(), order.get()); }
If either subtask fails, ShutdownOnFailure cancels the other automatically, so you never end up with an orphaned virtual thread quietly running after the scope has already reported failure.
More Related questions...