Working with Structured Concurrency JAVA 21+ PREVIEW

1. Understanding StructuredTaskScope

ConceptDetail
GoalTreat group of subtasks as single unit
LifetimeBounded by enclosing scope
CancellationPropagates to all subtasks
ReplacesManual ExecutorService + futures management

2. Creating Structured Task Scopes

ClassStrategy
ShutdownOnFailureCancel siblings on first failure
ShutdownOnSuccess<T>Cancel siblings on first success
CustomExtend 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());
}
MethodDetail
fork(callable)Start subtask
join()Wait for completion
throwIfFailed()Propagate failure

4. Using ShutdownOnSuccess Strategy

MethodDetail
fork(callable)Start racing subtask
join()Wait for first success
result()Return first success
Use caseRace multiple replicas, take fastest

5. Forking Subtasks

AspectDetail
Backed byVirtual threads
ReturnsSubtask<T>
Resultsubtask.get() after join()

6. Joining Subtasks

MethodDetail
join()Wait for all (or shutdown)
joinUntil(deadline)Timed wait

7. Handling Failures

MethodDetail
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();
}
MethodDetail
joinUntil(deadline)Throws TimeoutException
EffectCancels remaining subtasks

9. Cancelling Subtasks

MethodDetail
scope.shutdown()Cancel all + return immediately
Auto on closetry-with-resources cleans up

10. Comparing with Traditional Concurrency

AspectStructuredExecutorService
LifetimeLexically scopedManual
CancellationAutoManual
Error handlingCentralizedPer-future
Stack tracesHierarchicalFlat