Working with Structured Concurrency JAVA 21+ PREVIEW
1. Understanding StructuredTaskScope
| Concept | Detail |
|---|---|
| Goal | Treat group of subtasks as single unit |
| Lifetime | Bounded by enclosing scope |
| Cancellation | Propagates to all subtasks |
| Replaces | Manual ExecutorService + futures management |
2. Creating Structured Task Scopes
| Class | Strategy |
|---|---|
ShutdownOnFailure | Cancel siblings on first failure |
ShutdownOnSuccess<T> | Cancel siblings on first success |
| Custom | Extend StructuredTaskScope |
3. Using ShutdownOnFailure Strategy
Example: ShutdownOnFailure
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Subtask<User> userTask = scope.fork(() -> fetchUser(id));
Subtask<Order> orderTask = scope.fork(() -> fetchOrders(id));
scope.join(); // wait for all
scope.throwIfFailed(); // propagate first failure
return new Profile(userTask.get(), orderTask.get());
}
| Method | Detail |
|---|---|
fork(callable) | Start subtask |
join() | Wait for completion |
throwIfFailed() | Propagate failure |
4. Using ShutdownOnSuccess Strategy
| Method | Detail |
|---|---|
fork(callable) | Start racing subtask |
join() | Wait for first success |
result() | Return first success |
| Use case | Race multiple replicas, take fastest |
5. Forking Subtasks
| Aspect | Detail |
|---|---|
| Backed by | Virtual threads |
| Returns | Subtask<T> |
| Result | subtask.get() after join() |
6. Joining Subtasks
| Method | Detail |
|---|---|
join() | Wait for all (or shutdown) |
joinUntil(deadline) | Timed wait |
7. Handling Failures
| Method | Detail |
|---|---|
throwIfFailed() | Throws ExecutionException |
throwIfFailed(fn) | Custom exception mapping |
subtask.state() | SUCCESS / FAILED / UNAVAILABLE |
8. Using Timeouts
Example: Deadline
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
scope.fork(() -> longRunning());
scope.joinUntil(Instant.now().plusSeconds(5));
scope.throwIfFailed();
}
| Method | Detail |
|---|---|
joinUntil(deadline) | Throws TimeoutException |
| Effect | Cancels remaining subtasks |
9. Cancelling Subtasks
| Method | Detail |
|---|---|
scope.shutdown() | Cancel all + return immediately |
| Auto on close | try-with-resources cleans up |
10. Comparing with Traditional Concurrency
| Aspect | Structured | ExecutorService |
|---|---|---|
| Lifetime | Lexically scoped | Manual |
| Cancellation | Auto | Manual |
| Error handling | Centralized | Per-future |
| Stack traces | Hierarchical | Flat |