Structured Concurrency


What is Structured Concurrency?

Structured concurrency is a programming paradigm that treats groups of concurrent tasks as a single unit of work. It ensures that:

  • All child tasks (subtasks) are completed before the parent task finishes.
  • If one task fails, the others are cancelled.
  • No task is left running in the background unintentionally.

Why Use It?

  • Simplifies concurrency: Easier to reason about task lifetimes.
  • Improves error handling: Fail-fast behavior—if one task fails, others are cancelled.
  • Avoids resource leaks: Tasks are scoped and cleaned up properly.
  • Enhances readability: Code structure mirrors logical flow, like structured programming.

⚙️ How It Works (Java Example with StructuredTaskScope)

  1. Create a scope using StructuredTaskScope.
  2. Fork subtasks inside the scope.
  3. Join the subtasks (wait for them to complete).
  4. Handle results or exceptions.
  5. Scope closes only when all tasks are done or cancelled.
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Future<String> user  = scope.fork(() -> fetchUser());
    Future<String> order = scope.fork(() -> fetchOrder());

    scope.join();           // Wait for all subtasks
    scope.throwIfFailed();  // Propagate exceptions

    return user.result() + order.result();
}

🌳 Benefits

  • Hierarchical task structure: Clear parent-child relationships.
  • Scoped lifetimes: Tasks can’t outlive their scope.
  • Predictable flow: Like structured programming with if, for, etc.