Structured Concurrency in Java 28: StructuredTaskScope and ScopedValue
Java 28 finalizes structured concurrency through JEP 543. After seven preview rounds, StructuredTaskScope becomes a permanent API in java.util.concurrent, with no changes from the JDK 27 preview.
Structured concurrency treats a group of related tasks as a single unit of work. If one subtask fails, the others can be cancelled. If the parent task completes, no subtask is left running in the background.
Table of Contents
- Why Structured Concurrency?
- Problems with Unstructured Concurrency
- StructuredTaskScope Basics
- Fork and Join
- Completion Policies
- Timeouts and Cancellation
- ScopedValue
- Real-World Example
- Best Practices
- FAQs
Why Structured Concurrency?
Modern applications often need to call multiple services in parallel. For example, an order details page may need user information, order data, payment status, and shipping updates.
Doing these calls sequentially is slow. Doing them with an unstructured executor is faster but introduces lifecycle problems: tasks may outlive the request, failures may be missed, and cancellation may be incomplete.
Structured concurrency solves this by tying subtasks to a lexical scope. When the scope ends, all subtasks are complete, cancelled, or shut down.
Benefits
- Clear task lifecycle and ownership.
- Automatic cancellation of sibling tasks on failure.
- Simpler error propagation.
- Better observability of concurrent work.
- No orphaned background tasks.
- Natural fit with virtual threads.
Problems with Unstructured Concurrency
Consider a typical executor-based implementation:
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
Future<User> userFuture = executor.submit(() -> userService.findUser(userId));
Future<Order> orderFuture = executor.submit(() -> orderService.findOrder(orderId));
User user = userFuture.get();
Order order = orderFuture.get();
This works, but it has weaknesses:
- If the order lookup fails, the user lookup may continue running.
- The executor must be shut down correctly.
- Cancellation must be handled manually.
- Timeouts require additional coordination.
- Task relationships are not visible in the code structure.
Structured concurrency addresses these issues by making the task group explicit.
StructuredTaskScope Basics
StructuredTaskScope is used with try-with-resources. The scope is opened, subtasks are forked, and the scope is joined before it closes.
Basic example
import java.util.concurrent.StructuredTaskScope;
public OrderDetails getOrderDetails(Long userId, Long orderId)
throws Exception {
try (var scope = StructuredTaskScope.open()) {
var userTask = scope.fork(() ->
userService.findUser(userId)
);
var orderTask = scope.fork(() ->
orderService.findOrder(orderId)
);
scope.join();
return new OrderDetails(
userTask.get(),
orderTask.get()
);
}
}
What happens here
- The scope is opened.
- Two subtasks are forked.
join()waits for the subtasks.- Results are retrieved with
get(). - The scope closes and cleans up any remaining work.
Key rules
- Only the thread that opened the scope can fork subtasks.
- Subtasks must complete before the scope closes.
- If a subtask fails, the default policy cancels the others.
- Forked tasks should be short-lived and request-scoped.
Fork and Join
The fork method starts a subtask and returns a Subtask. The join method waits for subtasks according to the scope’s completion policy.
Forking multiple tasks
try (var scope = StructuredTaskScope.open()) {
var userTask = scope.fork(() ->
userService.findUser(userId)
);
var orderTask = scope.fork(() ->
orderService.findOrder(orderId)
);
var paymentTask = scope.fork(() ->
paymentService.findPayment(orderId)
);
scope.join();
User user = userTask.get();
Order order = orderTask.get();
Payment payment = paymentTask.get();
}
Subtask states
| State | Meaning |
|---|---|
| Forked | The subtask has been started but not completed |
| Successful | The subtask completed normally |
| Failed | The subtask threw an exception |
| Cancelled | The subtask was cancelled before completion |
Getting results safely
Call get() only after a successful join. If the subtask failed, get() throws an exception.
scope.join();
if (userTask.state() == StructuredTaskScope.Subtask.State.SUCCESS) {
User user = userTask.get();
}
Completion Policies
Structured concurrency supports different completion policies through joiners. The policy determines when join() returns.
Default policy: all must succeed
try (var scope = StructuredTaskScope.open()) {
// join() waits for all subtasks
// If any subtask fails, the others are cancelled
}
Wait for all, regardless of failure
import java.util.concurrent.StructuredTaskScope;
try (var scope = StructuredTaskScope.open(
StructuredTaskScope.Joiner.awaitAll()
)) {
var userTask = scope.fork(() -> userService.findUser(userId));
var orderTask = scope.fork(() -> orderService.findOrder(orderId));
scope.join();
// Inspect each subtask state individually
}
Return the first successful result
try (var scope = StructuredTaskScope.open(
StructuredTaskScope.Joiner.anySuccessfulResultOrThrow()
)) {
var primary = scope.fork(() -> primaryService.fetch(id));
var replica = scope.fork(() -> replicaService.fetch(id));
scope.join();
// The first successful result is available
}
Common joiner policies
| Joiner | Behavior |
|---|---|
awaitAllSuccessfulOrThrow() |
Waits for all subtasks; fails if any subtask fails |
awaitAll() |
Waits for all subtasks regardless of individual failures |
anySuccessfulResultOrThrow() |
Returns the first successful result and cancels the rest |
anySuccessfulOrThrow() |
Returns the first successful subtask and cancels the rest |
Timeouts and Cancellation
Timeouts are important for service calls. Structured concurrency supports timeouts directly on the scope.
Timeout example
import java.time.Duration;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.TimeoutException;
public OrderDetails getOrderDetails(Long userId, Long orderId)
throws Exception {
try (var scope = StructuredTaskScope.open(
StructuredTaskScope.Joiner.awaitAllSuccessfulOrThrow(),
config -> config.withTimeout(Duration.ofSeconds(2))
)) {
var userTask = scope.fork(() ->
userService.findUser(userId)
);
var orderTask = scope.fork(() ->
orderService.findOrder(orderId)
);
try {
scope.join();
} catch (TimeoutException ex) {
throw new OrderDetailsTimeoutException(
"Order details lookup timed out", ex
);
}
return new OrderDetails(
userTask.get(),
orderTask.get()
);
}
}
Cancellation behavior
- When the scope closes, unfinished subtasks are cancelled.
- When a subtask fails under the default policy, siblings are cancelled.
- Cancellation is cooperative and relies on interruption.
- Blocking operations should respond to interruption.
Handle interruption correctly
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException("Task interrupted", ex);
}
ScopedValue
ScopedValue provides immutable, inherited context for a bounded period of execution. It is designed as a safer alternative to ThreadLocal, especially when using virtual threads.
Why ScopedValue?
- Immutable for the duration of a scope.
- Automatically inherited by forked subtasks.
- No manual cleanup with
remove(). - Works well with structured concurrency.
- Avoids some of the memory and lifecycle issues of
ThreadLocal.
Basic ScopedValue example
import java.lang.ScopedValue;
public class RequestContext {
public static final ScopedValue<String> REQUEST_ID =
ScopedValue.newInstance();
public void handleRequest(String requestId) {
ScopedValue.where(REQUEST_ID, requestId)
.run(() -> processRequest());
}
private void processRequest() {
String requestId = REQUEST_ID.get();
System.out.println("Processing request " + requestId);
}
}
ScopedValue with a return value
public String handleRequest(String requestId) {
return ScopedValue.where(REQUEST_ID, requestId)
.call(() -> processRequest());
}
private String processRequest() {
return "Processed " + REQUEST_ID.get();
}
ScopedValue with structured concurrency
public OrderDetails getOrderDetails(Long userId, Long orderId)
throws Exception {
return ScopedValue.where(REQUEST_ID, "req-123")
.call(() -> {
try (var scope = StructuredTaskScope.open()) {
var userTask = scope.fork(() ->
userService.findUser(userId)
);
var orderTask = scope.fork(() ->
orderService.findOrder(orderId)
);
scope.join();
return new OrderDetails(
userTask.get(),
orderTask.get()
);
}
});
}
Forked subtasks inherit the scoped value binding, so services can access the request ID without passing it through every method call.
ScopedValue vs ThreadLocal
| Feature | ThreadLocal | ScopedValue |
|---|---|---|
| Mutability | Mutable | Immutable within scope |
| Cleanup | Manual | Automatic at scope end |
| Inheritance | Requires InheritableThreadLocal | Inherited by forked subtasks |
| Virtual thread friendliness | Can be problematic | Designed for modern concurrency |
| Best use | Legacy context propagation | Request context, tenant, security identity |
Real-World Example
Consider a product page that needs product details, inventory, reviews, and recommendations. Each call can run in parallel, but the page should fail fast if a required call fails.
import java.time.Duration;
import java.util.concurrent.StructuredTaskScope;
public ProductPage loadProductPage(Long productId)
throws Exception {
try (var scope = StructuredTaskScope.open(
StructuredTaskScope.Joiner.awaitAllSuccessfulOrThrow(),
config -> config.withTimeout(Duration.ofSeconds(3))
)) {
var productTask = scope.fork(() ->
productService.findProduct(productId)
);
var inventoryTask = scope.fork(() ->
inventoryService.findInventory(productId)
);
var reviewsTask = scope.fork(() ->
reviewService.findReviews(productId)
);
var recommendationsTask = scope.fork(() ->
recommendationService.findRecommendations(productId)
);
scope.join();
return new ProductPage(
productTask.get(),
inventoryTask.get(),
reviewsTask.get(),
recommendationsTask.get()
);
}
}
Why this design works
- All four calls run concurrently.
- A failure cancels the remaining calls.
- The timeout bounds the total wait time.
- No executor lifecycle management is required.
- The code structure mirrors the task structure.
Optional data with a fallback
Not every call should fail the page. Recommendations may be optional.
private List<Product> safeRecommendations(Long productId) {
try {
return recommendationService.findRecommendations(productId);
} catch (Exception ex) {
return List.of();
}
}
Fork the optional call separately or handle its failure inside the subtask so it does not cancel required work.
Best Practices
- Use structured concurrency for request-scoped fan-out work.
- Keep subtasks short-lived.
- Always use try-with-resources for the scope.
- Set timeouts for external service calls.
- Use
ScopedValuefor immutable request context. - Do not share mutable state between subtasks.
- Handle interruption correctly.
- Observe subtask failures and cancellation reasons.
- Avoid forking tasks that perform blocking I/O without timeouts.
Anti-pattern: fire-and-forget
// Avoid: work may be cancelled when the scope closes
try (var scope = StructuredTaskScope.open()) {
scope.fork(() -> auditService.recordEvent(event));
}
Structured concurrency is not designed for fire-and-forget background work. Use a proper background job mechanism for work that must outlive the request.
FAQs
Is structured concurrency final in Java 28?
Yes. JEP 543 finalizes structured concurrency in JDK 28 without API changes from the JDK 27 preview.
Do I need --enable-preview for StructuredTaskScope in Java 28?
No. Structured concurrency is final in Java 28, so preview features are not required for StructuredTaskScope.
What is the difference between StructuredTaskScope and ExecutorService?
ExecutorService manages tasks without a lexical relationship to the calling code. StructuredTaskScope ties subtasks to a scope, ensuring they complete or are cancelled before the scope exits.
What happens if one subtask fails?
Under the default policy, the remaining subtasks are cancelled and the failure is propagated. Other joiners allow different behavior.
Can I use StructuredTaskScope with virtual threads?
Yes. Structured concurrency is designed to work well with virtual threads and is a natural fit for request-scoped concurrent work.
What is ScopedValue used for?
ScopedValue provides immutable context for a bounded scope, such as a request ID, tenant ID, or security identity. It is inherited by forked subtasks.
Is ScopedValue a replacement for ThreadLocal?
It is a better choice for many new applications, especially those using virtual threads. Existing ThreadLocal usage can remain where it is still appropriate.
Can I use structured concurrency in Spring Boot?
Yes. It can be used inside service methods for parallel calls. Keep scopes request-scoped and avoid forking work that must outlive the request.
Final Thoughts
Structured concurrency gives Java a disciplined way to express concurrent work. StructuredTaskScope makes task lifetimes explicit, while ScopedValue provides safe context propagation without the drawbacks of mutable thread-local state.
Start with read-only fan-out operations such as loading a page from multiple services. Add timeouts, handle failures deliberately, and keep background work outside the scope.
Comments
Post a Comment