capypad
0 day streak
java / expert
Snippet

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.

snippet.java
java
1
2
3
4
5
6
7
8
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());
}
Breakdown
1
new StructuredTaskScope.ShutdownOnFailure()
Creates a scope that shuts down all forks if any single fork fails.
2
scope.fork(() -> ...)
Starts a subtask in a new virtual thread within the current scope.
3
scope.join().throwIfFailed()
Waits for all forks to finish and propagates the first exception if any occurred.