Structured Concurrency in Java: The Principles Behind StructuredTaskScope
The idea behind structured concurrency: subtasks live inside the block that forked them. The lifecycle (open, fork, join, close), the owner thread, and the rules the API enforces with WrongThreadException, IllegalStateException and StructureViolationException, each shown in a demo.
kvi5hnuCode Sprout team member8 min readOn this page
Article 26 showed what goes wrong when subtasks aren't tied to the code that started them. Structured concurrency fixes it with one rule borrowed from ordinary sequential code:
If a task splits into concurrent subtasks, they all return to the same place: the block that started them.
A method call can't outlive its caller, and its exception goes to its caller. Structured concurrency gives concurrent subtasks the same property. The subtasks of an operation form a tree under it, and the shape of that tree matches the shape of the code.
What the rule buys
With subtasks confined to a block:
- Errors propagate. A subtask's failure reaches the block that forked it, like an exception thrown by a method call.
- Cancellation propagates. If the operation fails or is abandoned, its unfinished subtasks are cancelled. There are no orphans.
- No leaks. When the block ends, every subtask has finished. Nothing keeps running in the background.
- Readable code. You can understand what a method does concurrently by reading the method. The block is the unit.
- Observability. The runtime knows the tree, so thread dumps can show which subtasks belong to which operation (article 36).
These are the guarantees the Java API is built around. The class is java.util.concurrent.StructuredTaskScope.
The four steps
Every use of StructuredTaskScope follows the same shape:
try (var scope = StructuredTaskScope.open()) { // 1. open
Subtask<Flight> flight = scope.fork(() -> findFlight(trip)); // 2. fork
Subtask<Hotel> hotel = scope.fork(() -> findHotel(trip));
scope.join(); // 3. join
return new Quote(flight.get(), hotel.get());
} // 4. close
- Open.
StructuredTaskScope.open()creates a scope. The thread that opens it is its owner. The no-argumentopen()uses the default policy: all subtasks must succeed, and the first failure cancels the rest. - Fork.
fork(Callable)orfork(Runnable)starts a subtask in a new thread, by default a new virtual thread, and returns aSubtaskhandle at once. - Join.
join()waits until the scope's policy is satisfied: here, until all subtasks succeed or one fails. If one fails, the scope cancels the others andjoin()throwsExecutionExceptionwith the failure as its cause. - Close. The end of the try-with-resources block calls
close(), which cancels any subtasks still running and waits until all of them have finished. Only then does the owner continue.

The try-with-resources block is the structure. Calling close() yourself is possible but there's no reason to: the block makes it impossible to forget, and it runs even when the owner throws.
The rules the API enforces
A scope isn't just a convention. It checks how it's used and throws if the structure is broken. The program below breaks each rule once. It uses the Java 27 preview API, so on Java 27 run it with java --enable-preview ScopeRules.java. On Java 28 no flag is needed.
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class ScopeRules {
interface Body { void run() throws Exception; }
static void attempt(String rule, Body body) {
try {
body.run();
System.out.println(rule + " -> ok");
} catch (Exception e) {
System.out.println(rule + " -> " + e.getClass().getSimpleName());
}
}
static String price() throws InterruptedException {
Thread.sleep(100);
return "EUR 412";
}
public static void main(String[] args) throws Exception {
attempt("1. read a result before join()", () -> {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> p = scope.fork(ScopeRules::price);
Thread.sleep(200); // the subtask has finished by now...
try { p.get(); } finally { scope.join(); } // ...but get() still refuses
}
});
attempt("2. fork() from a thread that isn't the owner", () -> {
try (var scope = StructuredTaskScope.open()) {
Exception[] failure = new Exception[1];
Thread.ofVirtual().start(() -> {
try { scope.fork(ScopeRules::price); } catch (Exception e) { failure[0] = e; }
}).join();
scope.join();
if (failure[0] != null) throw failure[0];
}
});
attempt("3. join() twice", () -> {
try (var scope = StructuredTaskScope.open()) {
scope.fork(ScopeRules::price);
scope.join();
scope.join();
}
});
attempt("4. fork() after join()", () -> {
try (var scope = StructuredTaskScope.open()) {
scope.fork(ScopeRules::price);
scope.join();
scope.fork(ScopeRules::price);
}
});
attempt("5. leave the block without join()", () -> {
try (var scope = StructuredTaskScope.open()) {
scope.fork(ScopeRules::price);
}
});
attempt("6. close an outer scope before an inner one", () -> {
var outer = StructuredTaskScope.open();
var inner = StructuredTaskScope.open();
outer.close();
});
// 7. The owner fails between fork() and join(): close() still cancels and waits
boolean[] interrupted = new boolean[1];
long start = System.nanoTime();
try (var scope = StructuredTaskScope.open()) {
scope.fork(() -> {
try { Thread.sleep(1000); } catch (InterruptedException e) { interrupted[0] = true; throw e; }
return "late";
});
throw new IllegalArgumentException("bad search request");
} catch (IllegalArgumentException e) {
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("7. owner threw " + e.getMessage() + "; subtask interrupted: " + interrupted[0]
+ "; block left in under 100 ms: " + (ms < 100)
+ "; suppressed: " + e.getSuppressed()[0].getClass().getSimpleName());
}
}
}
Output:
1. read a result before join() -> IllegalStateException
2. fork() from a thread that isn't the owner -> WrongThreadException
3. join() twice -> IllegalStateException
4. fork() after join() -> IllegalStateException
5. leave the block without join() -> IllegalStateException
6. close an outer scope before an inner one -> StructureViolationException
7. owner threw bad search request; subtask interrupted: true; block left in under 100 ms: true; suppressed: IllegalStateException
Each rule protects the structure:
- Results only after
join(). Even though the subtask had already finished,get()threw. Reading a result is allowed only after the owner has joined, so code can't depend on timing ("it's probably done by now"). The rule is about the owner's position in the code, not about the subtask's state.state(), by contrast, can be checked any time. - Only the owner forks, joins and closes. Another thread calling
forkgotWrongThreadException. A scope belongs to one thread, the same way a local variable belongs to one method call. Passing a scope to other threads would let subtasks be created outside the block. Subtasks themselves can still open their own scopes, which is how trees get deeper (article 35). - Join exactly once.
- No forking after
join(). Once the owner has collected the outcome, the set of subtasks is fixed. join()is mandatory. Forking and then leaving the block without joining is a programming error, reported byclose()asIllegalStateException. The scope still cancels and waits for the subtasks.- Scopes nest. A scope opened while another is open is nested in it, and must be closed first, the same way inner blocks end before outer ones. Closing the outer one first throws
StructureViolationException. With try-with-resources this can't happen. - Failures in the owner are safe too. The owner threw between
forkandjoin. Leaving the try block calledclose(), which interrupted the subtask and waited for it, so the block ended quickly with no subtask left running. The missingjoin()was reported as a suppressedIllegalStateExceptionon the owner's own exception, so the real error isn't lost.
Owner, subtasks and threads
- The owner is whatever thread opened the scope: a platform thread such as
main, a virtual thread handling a request, or a subtask of another scope. - Each forked subtask runs in its own new thread. With the default configuration that's a virtual thread, so forking is cheap and thousands of subtasks are fine. A different
ThreadFactorycan be configured (article 32). - Subtask threads aren't pooled. They start in
forkand end when their task ends. There's no executor to shut down, and the scope'sclose()is what guarantees they're all gone. - Cancellation means interrupting the subtask threads that are still running and refusing to start new ones. Subtasks must respond to interruption for cancellation to take effect, which blocking calls such as
sleep, socket reads andBlockingQueue.takedo. A subtask in a pure CPU loop keeps running until it checksThread.interrupted(), andclose()waits for it.
Policies decide when join() returns
The default open() encodes one policy: "all must succeed, first failure cancels". Other operations need other policies: "first success wins" for redundant mirrors, or "collect everything, successes and failures" for a dashboard. StructuredTaskScope separates the structure (open, fork, join, close, owner, nesting) from the policy, which is a Joiner passed to open. The next articles cover forking and subtasks in detail (article 28), the built-in joiners (articles 29 and 30), and writing your own (article 33).
What's current
StructuredTaskScopeis in its seventh preview in Java 27 (JEP 533) and final in Java 28 (JEP 543) with the same API. Java 21 to 24 had a class-based API with subclasses such asShutdownOnFailure. Java 25 introducedopen()andJoiner. Article 37 traces the changes.- On Java 27, compile and run with
--enable-preview(and--release 27when compiling). - The rules shown here (owner-only access, a single
join, results only afterjoin, nesting checks) have been the same since Java 25.
Common questions
Why can't I read a subtask's result before join(), even if it's finished?
Because whether it has finished depends on timing. Code that reads early would work on a fast machine and fail on a slow one. Requiring join() makes the code correct by its structure, not by luck.
Why must the owner be one thread? I want to fork from a callback. Because a scope models one block of code on one thread. If any thread could fork, subtasks could be created after the block's logic thinks it's done, or from code with no relationship to the block. To start work from another thread, that thread opens its own scope.
What happens if a subtask ignores interruption?
Cancellation can't force it to stop. close() waits until it finishes, so the block takes longer, but the structure still holds: no subtask outlives the block. Make long CPU loops check Thread.currentThread().isInterrupted().
Is StructuredTaskScope a replacement for ExecutorService?
For subtasks that are part of one operation, yes. For long-lived background work, worker pools, or tasks that intentionally outlive the request, an ExecutorService is still the right tool.
Summary
- Structured concurrency confines subtasks to the block that forked them, so errors and cancellation propagate and nothing leaks.
- A scope's life is open, fork, join, close, all on the owner thread, usually inside try-with-resources.
- The default
open()waits for all subtasks to succeed, cancels the rest on the first failure, and makesjoin()throwExecutionException. - The API enforces the structure:
WrongThreadExceptionfor non-owner threads,IllegalStateExceptionfor reading results beforejoin, joining twice, forking afterjoinor skippingjoin, andStructureViolationExceptionfor closing scopes out of order. close()always cancels unfinished subtasks and waits for all of them, even when the owner fails.
Practice questions
A developer passes a scope to a helper method that runs on a different thread, and the helper calls scope.fork(...). What happens, and what should the helper do instead?
Answer
fork throws WrongThreadException, because only the owner thread can fork. If the helper needs concurrent subtasks, it should open its own scope inside its own code. If the work belongs to the caller's operation, the owner should fork it.
The owner forks two subtasks, then a validation step in the owner throws before join(). Describe what happens when the try-with-resources block ends.
Answer
close() runs: it cancels (interrupts) both subtasks if they're still running, waits until both threads have finished, and then reports the missing join() as an IllegalStateException. Since the block is already exiting with the validation exception, that IllegalStateException is attached to it as a suppressed exception. The caller sees the validation exception, and no subtask is left running.
Why does Subtask.get() throw IllegalStateException before join() even when state() already reports SUCCESS?
Answer
The rule depends on where the owner is in the code, not on the subtask's state. Reading results only after join() means correctness can't depend on timing. state() is informational and can be checked at any time.
Previous: The Problems With Unstructured Concurrency in Java: Leaks, Lost Errors and Orphaned Tasks
Next: StructuredTaskScope in Java: fork(), join() and the Subtask Handle

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.