Interface TaskScope<T>
- All Superinterfaces:
AutoCloseable
A structured-concurrency scope that owns a group of sibling tasks and a shared cancellation
signal, and guarantees that none of those tasks outlive the scope's completion.
CompletableFuture<List<Data>> report = TaskScope.withScope(scope -> {
scope.attach(fetchData(1));
scope.attach(fetchData(2));
return scope.awaitAll();
});
-
Method Summary
Modifier and TypeMethodDescription<U> TaskChain<U> attach(CompletableFuture<U> future) Attaches an existing asynchronous task to this scope.default CompletableFuture<List<T>> awaitAll()Non-blocking fail-fast wait that completes with the collected task results in the order the tasks were attached.<R> CompletableFuture<R> Non-blocking fail-fast wait that collects all task results and passes them to a transformer.Non-blocking wait that completes with each collected task's settled outcome in the order the tasks were attached.voidCancels every task in this scope.voidclose()Cancels all tasks; idempotent.token()static <T,R> CompletableFuture <R> withScope(Function<TaskScope<T>, CompletableFuture<R>> body) Runs async work in a lexical scope and closes the scope when the returned future settles.
-
Method Details
-
token
CancellationToken<CancellationException> token()- Returns:
- the scope-wide cancellation token (tripped by
cancelAll()orclose()).
-
attach
Attaches an existing asynchronous task to this scope. Scope cancellation requests cancellation on the attached future. -
cancelAll
void cancelAll()Cancels every task in this scope. -
awaitAll
Non-blocking fail-fast wait that completes with the collected task results in the order the tasks were attached.This method does not close the scope. Scope lifetime remains caller-owned.
-
awaitAll
Non-blocking fail-fast wait that collects all task results and passes them to a transformer.The returned future completes after all collected tasks complete successfully. Attached tasks are collected by default; when a collected task is transformed, the transformed child replaces its parent in the collected result list. On first failure or cancellation it completes exceptionally and cancels unfinished tasks.
This method does not close the scope. Scope lifetime remains caller-owned.
-
awaitAllSettled
CompletableFuture<List<Result<T>>> awaitAllSettled()Non-blocking wait that completes with each collected task's settled outcome in the order the tasks were attached.Task failures and cancellations are returned as
Resultvalues instead of completing the returned future exceptionally.This method does not close the scope. Scope lifetime remains caller-owned.
-
close
void close()Cancels all tasks; idempotent. Cancellation settles every attached and derived future.- Specified by:
closein interfaceAutoCloseable
-
withScope
Runs async work in a lexical scope and closes the scope when the returned future settles. The returned future does not complete until every task attached inbodyhas settled, so no task outlives the scope.
-