ReviseAlgo Logo

Modern Java Features

Structured Concurrency

Manage concurrent tasks as a single unit of work using Structured Concurrency (Preview).

Interview: Tests how structured concurrency resolves thread leaks, task cancellation propagation, and error containment.

Last Updated: June 13, 2026 10 min read

Structured Concurrency organizes multi-threaded code by treating groups of concurrent tasks running in different threads as a single unit of work, simplifying error handling and cancellation.

Core Idea

Tasks spawned in a scope must return to the scope, preventing orphaned thread leaks.

Why It Matters

If one sub-task fails, all other sub-tasks are cancelled automatically, saving CPU cycles.

Interview Lens

Tests comparing structured concurrency scopes with legacy ExecutorService submit patterns.

Scope Scenarios

Java provides two standard structured concurrency scopes:

  • ShutdownOnFailure: Runs tasks in parallel and throws an exception if any task fails. Used for "AND" relations (all results needed).
  • ShutdownOnSuccess: Runs tasks in parallel and returns the result of the first successful task, cancelling the rest. Used for "OR" relations (fastest response wins).

Code Walkthrough

This program demonstrates fetching data concurrently using the ShutdownOnFailure scope.

import java.util.concurrent.StructuredTaskScope;
import java.util.function.Supplier;

public class ConcurrencyScopeDemo { public static void main(String[] args) throws Exception { try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { // Fork parallel tasks Supplier user = scope.fork(() -> "User info"); Supplier order = scope.fork(() -> "Order details");

scope.join(); // Wait for all forks to complete scope.throwIfFailed(); // Propagate errors if any fork failed

System.out.println(user.get() + " & " + order.get()); } } }

Interview-Relevant Information

Q: How does structured concurrency solve the thread leak issue of ExecutorService?
Answer: In legacy code using ExecutorService, if a method submitting tasks exits due to an exception, the background threads keep running independently (thread leaks). In Structured Concurrency, the try-with-resources block forces the scope to close, automatically cancelling and cleaning up any remaining threads.

Quick Checklist

What is the difference between ShutdownOnFailure and ShutdownOnSuccess? How are threads cleaned up when an exception occurs? If yes, you understand Structured Concurrency.

Use Cases

Combining microservice data fetch branches safely.

Parallelizing database reads with fail-fast cancellation.

Common Mistakes

Calling Supplier.get() before calling scope.join(), which throws IllegalStateException.

Bypassing try-with-resources configurations, which can leak scopes if exceptions occur.