Interface TaskScope<T>

All Superinterfaces:
AutoCloseable

public interface TaskScope<T> extends 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 Details

    • token

      Returns:
      the scope-wide cancellation token (tripped by cancelAll() or close()).
    • attach

      <U> TaskChain<U> attach(@Nonnull CompletableFuture<U> future)
      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

      default CompletableFuture<List<T>> 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

      <R> CompletableFuture<R> awaitAll(Function<List<T>,R> resultTransformer)
      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 Result values 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:
      close in interface AutoCloseable
    • withScope

      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. The returned future does not complete until every task attached in body has settled, so no task outlives the scope.