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) |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
