Java / Java 21 Interview Questions
What is Structured Concurrency in Java 21 and what problem does it solve?
Structured Concurrency (JEP 453, second preview in Java 21) is an API — built on StructuredTaskScope — that treats a group of concurrent subtasks as a single unit of work whose lifetime is scoped to the code block that created them. It solves the problem of unreliable cancellation, lost exceptions, and dangling threads that plague ad-hoc ExecutorService usage.
// Classic problem: if userTask or orderTask throws, the other leaks
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
// Fork subtasks — each runs on its own virtual thread
Subtask userTask = scope.fork(() -> fetchUser(userId));
Subtask orderTask = scope.fork(() -> fetchOrder(orderId));
scope.join() // wait for both
.throwIfFailed(); // propagate first failure as exception
// Both succeeded — safe to access results
return new Response(userTask.get(), orderTask.get());
} // scope.close() cancels any still-running subtasks automatically
// ShutdownOnSuccess — return the first result that succeeds
try (var scope = new StructuredTaskScope.ShutdownOnSuccess()) {
scope.fork(() -> callPrimaryService());
scope.fork(() -> callFallbackService());
scope.join();
return scope.result(); // whichever finished first
} The key guarantee is the structure invariant: a subtask never outlives the scope that forked it. When control leaves the try block (normally or via exception), StructuredTaskScope.close() cancels all still-running subtasks and waits for them to finish — preventing thread leaks entirely.
| Policy | Shuts down scope when... | Use case |
|---|---|---|
| ShutdownOnFailure | Any subtask fails | All subtasks must succeed (fan-out + join) |
| ShutdownOnSuccess | Any subtask succeeds | First result wins (hedged request) |
More Related questions...