Java / Java 21 Interview Questions
When should you use StructuredTaskScope instead of CompletableFuture in Java 21?
Both APIs manage concurrent asynchronous work, but they have different designs, guarantees, and ideal use cases. Java 21 introduces StructuredTaskScope as the preferred model when running on virtual threads.
| Aspect | CompletableFuture | StructuredTaskScope |
|---|---|---|
| API style | Callback/continuation chain | Imperative — fork, then join |
| Cancellation | Manual — no automatic cleanup | Automatic — scope closes all tasks on exit |
| Error propagation | Manual — must handle in chain | throwIfFailed() re-throws cleanly |
| Thread model | ForkJoinPool (platform threads) or custom executor | Virtual threads (one per fork) |
| Structure | Unstructured — tasks can outlive scope | Structured — subtasks never outlive scope |
| Stack traces | Fragmented across continuations | Full linear traces per virtual thread |
| Availability | Java 8+ | Java 21 (preview) |
// CompletableFuture — unstructured, manual cancellation
CompletableFuture userF = CompletableFuture.supplyAsync(() -> fetchUser(id));
CompletableFuture orderF = CompletableFuture.supplyAsync(() -> fetchOrder(id));
// If fetchUser throws, fetchOrder may continue running — thread leak possible
String result = userF.thenCombine(orderF,
(u, o) -> u.name() + " / " + o.total()).join();
// StructuredTaskScope — structured, automatic cleanup
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var userTask = scope.fork(() -> fetchUser(id));
var orderTask = scope.fork(() -> fetchOrder(id));
scope.join().throwIfFailed(); // if either fails, closes both
String result2 = userTask.get().name() + " / " + orderTask.get().total();
} // scope.close() cancels any still-running tasks
// Choose CompletableFuture when:
// - Integrating with existing CF-based APIs
// - You need complex transformation pipelines on the result
// - You cannot use preview features
// Choose StructuredTaskScope when:
// - You want automatic cancellation and no thread leaks
// - Code runs on virtual threads (Java 21)
// - You want structured, readable concurrent code
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...
