Structured Concurrency with StructuredTaskScope
Structured Task Scope (Preview in Java 21+) treats groups of related tasks running in different threads as a single unit of work. ShutdownOnFailure ensures that if one subtask fails, all other related virtual threads are automatically cancelled, preventing 'orphan' threads and improving observability.
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {Supplier<String> user = scope.fork(() -> fetchUser(id));Supplier<Integer> order = scope.fork(() -> fetchOrder(id));scope.join().throwIfFailed();return new Dashboard(user.get(), order.get());}