1. Introduction
When threads each play their own part
Conventional multithreading often feels like a rehearsal without a conductor. Each thread is like a musician playing their own tune without listening to the others. Someone finishes early and goes for a smoke, someone gets stuck on a single chord, someone even mixes up the notes and throws an error. The result is not a symphony but a cacophony: figuring out who went off beat is nearly impossible, and stopping everyone at once is a quest of its own.
Structured Concurrency solves this. It turns a set of disparate threads into a real ensemble: all tasks are united under a single “conductor.” If the conductor calls it off, the orchestra goes silent. If one musician messes up, the others stop gracefully without breaking the harmony. All results and errors are collected centrally rather than scattered around the code.
Imagine: you don’t let the musicians play whatever they want; you bring them into one hall. There’s a conductor, there’s a score, and even if the trumpet plays out of tune, the orchestra doesn’t fall apart but ends the performance gracefully.
What Structured Concurrency gives you
- Single task scope: all subtasks live within one block of code; their lifecycle is bounded by that block.
- Predictable completion: the parent thread won’t finish until all subtasks complete.
- Centralized cancellation: if one task fails or the parent decides to finish, all subtasks are canceled cleanly.
- Consistent error handling: subtask errors are aggregated; you can get a “tree of causes.”
- Clean, readable code: no dangling threads, no forgotten tasks, no races to cancel.
Structured Concurrency is not just a new API, it’s a new mindset: tasks should be structured just like ordinary code blocks (for example, try-with-resources).
2. Structured Concurrency status in Java
At the time of writing, Structured Concurrency is in Preview status (Java 21–23), but it’s expected to move toward GA (General Availability) in Java 24/25. The API resides in the jdk.incubator.concurrent package. Before using in production, be sure to check the current release notes for your JDK version!
Main classes:
- StructuredTaskScope — the base class for managing a group of tasks.
- Variants: StructuredTaskScope.ShutdownOnFailure, StructuredTaskScope.ShutdownOnSuccess — task termination policies.
Core concepts of StructuredTaskScope
Model: fork, join, and a friendly roll call of results
When the conductor (that is, the parent task) gives the sign, the subtasks run off to play their parts. This moment is called fork — as if you launch the musicians to play their pieces in different halls.
Then comes the time to join — the conductor raises the baton, and everyone returns to play the final chord together.
After that, you can ask each participant how it went:
- via resultNow() to get the result immediately if everything finished without errors;
- via throwIfFailed() — to make sure no one hit a wrong note. If someone did get lost, a single exception is thrown — as if the conductor said: “We have a failure in the orchestra; starting over.”
Termination policies
Every conductor has their own rule for when to stop the music. In Structured Concurrency this is defined by a termination policy:
- ShutdownOnFailure — if even one musician loses the beat, the conductor waves a hand: “Stop! From the top.” The others immediately stop playing.
- ShutdownOnSuccess — on the contrary, as soon as someone plays their part perfectly, the conductor is satisfied: “That’s enough, we already have a winner.” The rest go silent — the first-success policy.
Working with virtual threads
Each subtask in StructuredTaskScope runs in a virtual thread. It’s like having an orchestra where every musician is quick and agreeable, with no diva demands. You can safely create hundreds or thousands of such performers — they’re not heavyweight OS threads but almost weightless notes that sound exactly when needed.
3. Example: HTTP request aggregator
Let’s consider a practical task: we have three data sources (for example, three different servers), and we want to get a response either from all of them (and aggregate) or from the first one that succeeds.
Variant 1: “All must succeed” (ShutdownOnFailure)
import jdk.incubator.concurrent.StructuredTaskScope;
import java.util.concurrent.Future;
public class AggregatorAllSuccess {
public static void main(String[] args) throws Exception {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> f1 = scope.fork(() -> fetchFromSource1());
Future<String> f2 = scope.fork(() -> fetchFromSource2());
Future<String> f3 = scope.fork(() -> fetchFromSource3());
scope.join(); // wait for all tasks to complete
scope.throwIfFailed(); // if any failed, throw an exception
// All tasks succeeded — safe to aggregate results
String result = f1.resultNow() + f2.resultNow() + f3.resultNow();
System.out.println("Aggregated result: " + result);
}
}
static String fetchFromSource1() { /* ... */ return "A"; }
static String fetchFromSource2() { /* ... */ return "B"; }
static String fetchFromSource3() { /* ... */ return "C"; }
}
What happens:
- All three tasks are launched in parallel (in virtual threads).
- If at least one fails, the rest are canceled and an exception is thrown.
- If all succeed, you can safely aggregate the results.
Variant 2: “First successful wins” (ShutdownOnSuccess)
import jdk.incubator.concurrent.StructuredTaskScope;
import java.util.concurrent.Future;
public class AggregatorFirstSuccess {
public static void main(String[] args) throws Exception {
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) {
Future<String> f1 = scope.fork(() -> fetchFromSource1());
Future<String> f2 = scope.fork(() -> fetchFromSource2());
Future<String> f3 = scope.fork(() -> fetchFromSource3());
scope.join(); // wait for the first success
scope.throwIfFailed(); // if all failed, throw an exception
String result = scope.result(); // result of the first successful task
System.out.println("First successful result: " + result);
}
}
static String fetchFromSource1() { /* ... */ return "A"; }
static String fetchFromSource2() { /* ... */ return "B"; }
static String fetchFromSource3() { /* ... */ return "C"; }
}
What happens:
- As soon as one task completes successfully, the rest are canceled.
- If all fail, an exception is thrown.
4. Automatic cancellation and graceful degradation
StructuredTaskScope takes care of canceling the remaining tasks when the policy requires it. For example, if one task fails (ShutdownOnFailure) or one completes successfully (ShutdownOnSuccess), the remaining tasks receive an interruption signal (interrupt).
Example: clean shutdown with a timeout
import jdk.incubator.concurrent.StructuredTaskScope;
import java.time.Instant;
import java.util.concurrent.Future;
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> f1 = scope.fork(() -> fetchWithTimeout());
Future<String> f2 = scope.fork(() -> fetchWithTimeout());
scope.joinUntil(Instant.now().plusSeconds(2)); // wait at most 2 seconds
scope.throwIfFailed();
String result = f1.resultNow() + f2.resultNow();
System.out.println(result);
}
If the tasks do not finish within 2 seconds, an exception will be thrown and all tasks will be canceled.
5. Errors and exception handling
How subtask exceptions are routed to the scope
Sometimes during the concert someone still misses a note — StructuredTaskScope doesn’t pretend nothing happened. It carefully records who played out of tune and then hands the conductor a full report. When you call throwIfFailed(), it throws an aggregated exception — something like a summary report: “Here’s the list of those who hit a wrong note today.” If needed, you can expand this “tree of causes” and see who exactly fell short. And if you want to know about a specific performer, Future.exceptionNow() will tell you how their part ended.
When cancellation is not a failure
It’s important to remember: canceling a task doesn’t always mean an error. If the conductor says “the concert is over,” the musicians simply put away their instruments — that’s cancelled, not failed. An error is only when someone actually played the wrong thing, and that exception will be included in the overall summary.
Example: tree of causes
import jdk.incubator.concurrent.StructuredTaskScope;
import java.util.concurrent.Future;
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> f1 = scope.fork(() -> { throw new RuntimeException("Error 1"); });
Future<String> f2 = scope.fork(() -> { throw new RuntimeException("Error 2"); });
scope.join();
scope.throwIfFailed(); // will throw an exception with both causes
} catch (Exception e) {
e.printStackTrace();
// You can get suppressed exceptions via e.getSuppressed()
}
6. Comparison with CompletableFuture
StructuredTaskScope and CompletableFuture both let you run parallel tasks, but:
- StructuredTaskScope is convenient when tasks are logically related and should complete/cancel together (a task hierarchy).
- CompletableFuture is great for composing tasks without a hierarchy (for example, transformation chains, reactive scenarios).
When StructuredTaskScope makes code simpler:
- When you must ensure all subtasks finish before exiting a block.
- When you need centralized cancellation and error handling.
- When it’s important not to leave any “dangling” tasks.
When CompletableFuture is more convenient:
- When tasks are unrelated and can live independently.
- When you need complex composition (thenCombine, thenCompose, etc.).
7. Practice: HTTP request aggregator
Task: send requests to 3 sources and get the first successful response
import jdk.incubator.concurrent.StructuredTaskScope;
import java.util.concurrent.Future;
public class HttpAggregator {
public static void main(String[] args) throws Exception {
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) {
Future<String> f1 = scope.fork(() -> httpRequest("https://api1.example.com"));
Future<String> f2 = scope.fork(() -> httpRequest("https://api2.example.com"));
Future<String> f3 = scope.fork(() -> httpRequest("https://api3.example.com"));
scope.join();
scope.throwIfFailed();
String result = scope.result();
System.out.println("First successful response: " + result);
}
}
static String httpRequest(String url) throws Exception {
// Request simulation (you can use HttpClient)
Thread.sleep((long) (Math.random() * 1000));
if (Math.random() < 0.3) throw new RuntimeException("Request error: " + url);
return "Response from " + url;
}
}
Task: if one subtask fails, shut down the rest cleanly
import jdk.incubator.concurrent.StructuredTaskScope;
import java.util.concurrent.Future;
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> f1 = scope.fork(() -> httpRequest("https://api1.example.com"));
Future<String> f2 = scope.fork(() -> httpRequest("https://api2.example.com"));
scope.join();
scope.throwIfFailed();
String result = f1.resultNow() + f2.resultNow();
System.out.println("Both responses: " + result);
} catch (Exception e) {
System.err.println("Error in one of the tasks: " + e.getMessage());
}
8. Common pitfalls when working with StructuredTaskScope
Mistake #1: forgot to call join() or throwIfFailed().
If you don’t call join(), tasks may not complete before leaving the block. If you don’t call throwIfFailed(), subtask errors will go unnoticed.
Mistake #2: attempting to get a result before the task completes.
Calling resultNow() before the task completes will throw an IllegalStateException. First wait for completion via join().
Mistake #3: ignoring cancellation.
If a task was canceled (for example, due to the scope policy), don’t try to get its result — you’ll get an exception.
Mistake #4: mixing different termination policies.
Don’t try to cancel tasks manually inside a scope — use the ShutdownOnFailure or ShutdownOnSuccess policies.
Mistake #5: running long CPU-bound tasks on virtual threads.
StructuredTaskScope uses virtual threads by default — they’re ideal for I/O-bound tasks but won’t speed up heavy computations.
Mistake #6: forgetting to close the scope (no try-with-resources).
StructuredTaskScope implements AutoCloseable — always use try-with-resources to ensure all tasks terminate.
GO TO FULL VERSION