Java applications often perform multiple operations at the same time. A service might retrieve customer details, check inventory, calculate pricing, and request delivery information before returning a response.
These operations can run concurrently to reduce waiting time. However, managing related tasks with traditional threads, executors, and futures can become complicated.
Developers must coordinate task completion, handle failures, cancel unfinished operations, and ensure that background work does not continue after the main request has already failed.
Structured concurrency provides a way to organize related concurrent tasks around a clear parent-child relationship. Instead of treating every task as an independent operation, it allows developers to manage a group of tasks within a defined scope.
Java introduced structured concurrency through its preview APIs in recent releases. Because these APIs have evolved across JDK versions, developers should check the documentation for the specific Java version they use before adopting them.
This article explains structured concurrency, how it differs from traditional concurrency approaches, and how to use it to manage related Java tasks.
What Is Structured Concurrency?
Structured concurrency is a programming approach in which concurrent tasks are organized into a defined scope.
The parent operation creates child tasks, waits for their completion, and handles their results before the scope ends.
For example, consider an application that needs three independent operations:
Retrieve customer information.
Check product availability.
Calculate the order total.
With an unstructured approach, each operation might be submitted independently to an executor. The application then needs to track every future and determine what happens if one operation fails.
With structured concurrency, these tasks belong to a single operation. Their lifecycle is connected to the parent request.
The main idea is that a task should not unexpectedly outlive the operation responsible for it.
A structured task scope helps establish this relationship.
Why Traditional Concurrency Can Become Difficult
Java provides several concurrency APIs, including Thread, ExecutorService, Future, and CompletableFuture.
These APIs are useful, but coordinating multiple related operations requires careful lifecycle management.
Consider this example using CompletableFuture:
import java.util.concurrent.CompletableFuture;
public class OrderService {
public void processOrder() {
CompletableFuture<String> customerFuture =
CompletableFuture.supplyAsync(
() -> "Customer details"
);
CompletableFuture<String> inventoryFuture =
CompletableFuture.supplyAsync(
() -> "Inventory available"
);
CompletableFuture<String> pricingFuture =
CompletableFuture.supplyAsync(
() -> "Order price calculated"
);
CompletableFuture<Void> result =
CompletableFuture.allOf(
customerFuture,
inventoryFuture,
pricingFuture
);
result.join();
System.out.println(customerFuture.join());
System.out.println(inventoryFuture.join());
System.out.println(pricingFuture.join());
}
}This example executes independent operations concurrently.
However, several concerns remain:
The developer must coordinate all futures.
Failure handling needs additional planning.
Cancellation behavior must be considered.
The relationship between the parent operation and child tasks is not represented by a dedicated scope.
Unfinished operations may continue consuming resources if lifecycle management is incomplete.
These concerns become more difficult when a service has many concurrent operations or nested asynchronous workflows.
Understanding Java Structured Concurrency APIs
Java's structured concurrency APIs have been introduced and refined through preview releases.
The StructuredTaskScope API provides a mechanism for creating and managing related tasks.
A task scope generally follows this lifecycle:
Create a task scope.
Fork child tasks.
Join the tasks.
Handle task results or failures.
Close the scope.
The scope provides a boundary for the concurrent operations.
The exact API names, constructors, and policy classes have changed across preview iterations. Therefore, examples must target a specific JDK release rather than assuming that code from an earlier preview will compile unchanged on a newer release.
The following sections illustrate the core design using the Java 21 preview API.
Creating Concurrent Tasks With StructuredTaskScope
In the Java 21 preview API, StructuredTaskScope can be used to start multiple related tasks.
The following example retrieves customer and inventory information concurrently.
import java.util.concurrent.StructuredTaskScope;
public class OrderService {
public void processOrder() throws Exception {
try (var scope =
new StructuredTaskScope.ShutdownOnFailure()) {
var customerTask = scope.fork(
() -> getCustomerDetails()
);
var inventoryTask = scope.fork(
() -> checkInventory()
);
scope.join();
scope.throwIfFailed();
String customer = customerTask.get();
String inventory = inventoryTask.get();
System.out.println(customer);
System.out.println(inventory);
}
}
private String getCustomerDetails() {
return "Customer details retrieved";
}
private String checkInventory() {
return "Inventory available";
}
}This example demonstrates several important concepts.
Forking child tasks
In the Java 21 preview API, StructuredTaskScope can be used to start multiple related tasks.
var customerTask = scope.fork(
() -> getCustomerDetails()
);The returned subtask represents the operation. The parent can retrieve its result after the scope has joined the tasks.
Waiting for completion
The join() method waits for the child tasks to finish.
scope.join();The parent operation does not continue to process the results until the required tasks have completed.
Handling failures
The ShutdownOnFailure policy requests shutdown of the remaining tasks when a child task fails.
The following call checks whether a task failed:
scope.throwIfFailed();If a failure occurred, the method propagates it rather than allowing the application to continue as if every operation succeeded.
Closing the scope
The try-with-resources statement ensures that the scope is closed.
try (var scope =
new StructuredTaskScope.ShutdownOnFailure()) {Closing the scope is part of its lifecycle management. The parent operation should not leave child tasks running without considering their completion and cancellation.
Understanding ShutdownOnFailure and ShutdownOnSuccess
Structured concurrency supports different task coordination policies.
The Java 21 preview API included policies such as ShutdownOnFailure and ShutdownOnSuccess.
ShutdownOnFailure
Use this approach when all required operations must succeed.
For example, an order cannot be confirmed unless customer validation and inventory verification both succeed.
try (var scope =
new StructuredTaskScope.ShutdownOnFailure()) {
var customerTask = scope.fork(
() -> validateCustomer()
);
var inventoryTask = scope.fork(
() -> verifyInventory()
);
scope.join();
scope.throwIfFailed();
System.out.println(customerTask.get());
System.out.println(inventoryTask.get());
}If one task fails, the scope requests cancellation of the other unfinished tasks.
This avoids continuing unnecessary work when the overall operation cannot succeed.
ShutdownOnSuccess
Use this policy when the application needs the first successful result from multiple independent alternatives.
For example, a service might query two independent data sources and accept the first successful response.
In the Java 21 preview API, the pattern looked like this:
try (var scope =
new StructuredTaskScope.ShutdownOnSuccess<String>()) {
scope.fork(() -> queryPrimaryService());
scope.fork(() -> querySecondaryService());
String result = scope.join()
.result();
System.out.println(result);
}This approach can be useful for fallback services or redundant read operations.
However, it should not be used when every task must complete or when the results need to be combined.
Combining Results From Multiple Tasks
Many application workflows need results from several operations rather than only one successful response.
For example, a dashboard might need customer information, order history, and account status.
The following example demonstrates this pattern using the Java 21 preview API:
import java.util.concurrent.StructuredTaskScope;
public class DashboardService {
public void loadDashboard() throws Exception {
try (var scope =
new StructuredTaskScope.ShutdownOnFailure()) {
var customerTask =
scope.fork(() -> getCustomer());
var orderTask =
scope.fork(() -> getOrders());
var accountTask =
scope.fork(() -> getAccountStatus());
scope.join();
scope.throwIfFailed();
Dashboard dashboard = new Dashboard(
customerTask.get(),
orderTask.get(),
accountTask.get()
);
display(dashboard);
}
}
private String getCustomer() {
return "Customer information";
}
private String getOrders() {
return "Order history";
}
private String getAccountStatus() {
return "Account active";
}
private void display(Dashboard dashboard) {
System.out.println(dashboard);
}
record Dashboard(
String customer,
String orders,
String accountStatus
) {}
}The three operations run concurrently, and their results are combined after successful completion.
This structure makes the relationship between the parent request and child operations easier to understand.
Structured Concurrency and Virtual Threads
Structured concurrency works particularly well with virtual threads.
Virtual threads are lightweight threads designed to support a large number of concurrent tasks without requiring one operating-system thread for every task.
A virtual thread can execute blocking operations, such as network calls, without requiring developers to manage a large number of platform threads.
Structured concurrency focuses on task organization and lifecycle management, while virtual threads provide a lightweight execution model.
They solve related but different problems.
For example:
Feature | Structured Concurrency | Virtual Threads |
|---|---|---|
Main purpose | Organize related tasks | Provide lightweight threads |
Focus | Task lifecycle and coordination | Thread execution |
Failure handling | Supports scope-based policies | Uses normal exception handling |
Cancellation | Coordinates child task shutdown | Supports interruption |
Typical use | Managing related operations | Handling many concurrent tasks |
Using virtual threads does not automatically make an application structured. Developers still need to manage task relationships, cancellation, and error handling.
Likewise, structured concurrency can be understood independently of the execution mechanism used by a task.
Handling Exceptions and Cancellation
Failure handling is one of the most important reasons to consider structured concurrency.
Suppose an application starts three tasks:
Validate a customer.
Check inventory.
Calculate shipping charges.
If customer validation fails, there may be no reason to continue checking inventory or calculating shipping.
A failure-oriented scope can request shutdown of unfinished tasks.
However, cancellation is not the same as forcibly stopping arbitrary code.
Java generally uses interruption as a cooperative cancellation mechanism. Tasks should respond appropriately to interruption rather than swallowing it.
For example:
private String callExternalService() throws InterruptedException {
try {
Thread.sleep(2000);
return "Service response";
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw ex;
}
}This example restores the interrupt status before propagating the exception.
In real applications, network clients, database drivers, and other libraries must also have appropriate timeout and cancellation behavior.
Structured concurrency cannot guarantee immediate cancellation if a child task is blocked in code that does not respond to interruption.
Structured Concurrency vs CompletableFuture
Both approaches support concurrent operations, but they offer different programming models.
Area | Structured Concurrency | CompletableFuture |
|---|---|---|
Task organization | Scope-based parent-child structure | Completion-stage composition |
Result handling | Subtask results within a scope | Future completion methods |
Failure coordination | Scope policies | Exception-handling stages |
Cancellation | Scope coordinates child shutdown | Cancellation requires careful composition |
Programming style | Often direct and sequential-looking | Often asynchronous pipelines |
Best suited for | Related tasks with a shared lifecycle | Asynchronous composition and event-driven workflows |
Neither approach replaces the other in every situation.
CompletableFuture remains useful when building asynchronous pipelines, composing independent completion stages, or integrating with APIs that already use futures.
Structured concurrency is especially useful when several tasks belong to one request and should be managed together.
Common Mistakes to Avoid
Assuming structured concurrency automatically prevents resource leaks
Structured scopes improve lifecycle management, but child tasks still need proper resource handling.
Always close database connections, HTTP response bodies, files, and other resources correctly.
Ignoring interruption
A child task that ignores interruption may continue running after the parent operation requests shutdown.
Use interruption-aware APIs and configure timeouts for external operations.
Using the wrong coordination policy
ShutdownOnFailure is appropriate when every required operation must succeed.
ShutdownOnSuccess is appropriate when the first successful result is sufficient.
Choose a policy based on application requirements rather than convenience.
Assuming preview APIs are stable
Preview APIs can change between JDK releases. Code written for one preview version may not compile against another.
Check the API documentation and release notes for the exact JDK version used by your project.
Starting unnecessary concurrent work
Concurrency introduces coordination and resource-management costs.
Do not create separate tasks for operations that depend on one another or are too small to benefit from concurrent execution.
Best Practices for Production Applications
Group tasks that belong to the same request or business operation.
Choose a task coordination policy that matches the required outcome.
Use timeouts for database and external service calls.
Make child tasks responsive to interruption.
Avoid starting unnecessary background work.
Keep resource cleanup inside the appropriate task lifecycle.
Test failure, timeout, and cancellation scenarios.
Monitor thread usage, request latency, and external service failures.
Verify the exact structured concurrency API supported by the target JDK.
Avoid moving preview APIs into production without understanding the compatibility implications.
Advantages and Limitations
Structured concurrency offers several benefits:
Related tasks have a clearly defined lifecycle.
Child task failures can be coordinated.
Unfinished tasks can be asked to shut down when the parent operation fails.
Concurrent code can be easier to read and maintain.
Task ownership becomes clearer.
It also has limitations:
API availability and signatures depend on the JDK release.
Preview APIs can change.
Cancellation depends on tasks responding to interruption.
It does not automatically solve resource leaks or external service timeouts.
It may not be the best fit for long-running independent background jobs.
Developers still need to understand concurrency, synchronization, and shared-state safety.
Summary
Structured concurrency provides a way to manage related Java tasks as one coordinated operation. Instead of treating every concurrent task as an independent future, developers can organize child tasks inside a scope with a defined lifecycle.
The StructuredTaskScope API demonstrates how to fork tasks, wait for completion, handle failures, and coordinate shutdown. Policies such as ShutdownOnFailure and ShutdownOnSuccess support different application requirements in the Java 21 preview API.
Structured concurrency and virtual threads complement each other, but they address different concerns. Virtual threads make concurrent execution more lightweight, while structured concurrency helps developers manage task relationships and lifecycles.
For applications that perform multiple related operations within a request, this approach can make concurrent code easier to understand, test, and maintain. Before adopting it, verify the API version and compatibility requirements of the JDK used by your project.

Join the conversation! Your thoughts help the community grow.