Java Reference ยท Concurrency
Structured concurrency (StructuredTaskScope)
Reference for structured concurrency in Java: StructuredTaskScope (a preview API in Java 25), joiners, fork and join, plus runnable stand-ins with executors.
Structured concurrency treats a group of related tasks as one unit of work. A parent opens a scope, forks subtasks into it, waits for them in one place and leaves the scope only when every subtask has ended. If one subtask fails, the others can be cancelled; if the parent is interrupted, the subtasks are cancelled too. The lifetime of each thread is therefore visible in the shape of the code, like a block-structured try statement, and a task can no longer leak and run on after its caller has finished.
The API is java.util.concurrent.StructuredTaskScope. It is still a preview API in Java 25 (its fifth preview, JEP 505), so you must compile and run with --enable-preview, and its methods may change in a later release. Our online runner does not pass that flag, so the StructuredTaskScope snippets below are read-only, and the runnable examples use ordinary executors to show the same ideas.
The Java 25 preview API (read-only)
In Java 25 you open a scope with the static factory open(), optionally passing a Joiner that decides when the scope is finished and what join() returns.
// Needs: java --enable-preview --source 25 Main.java import java.util.concurrent.StructuredTaskScope; import java.util.concurrent.StructuredTaskScope.Subtask; String loadPage() throws Exception { // allSuccessfulOrThrow(): wait for all subtasks, cancel the rest if one fails try (var scope = StructuredTaskScope.open(StructuredTaskScope.Joiner.<String>allSuccessfulOrThrow())) { Subtask<String> user = scope.fork(() -> fetchUser()); Subtask<String> order = scope.fork(() -> fetchOrder()); scope.join(); // blocks until the joiner says "done" return user.get() + " / " + order.get(); // get() only after join() } }
// Race several sources and take the first success; the others are cancelled String fastest() throws Exception { try (var scope = StructuredTaskScope.open(StructuredTaskScope.Joiner.<String>anySuccessfulResultOrThrow())) { scope.fork(() -> queryMirrorA()); scope.fork(() -> queryMirrorB()); return scope.join(); // the first result } }
| Member | Description |
|---|---|
StructuredTaskScope.open() |
Opens a scope whose joiner waits for all subtasks and throws if any failed (awaitAllSuccessfulOrThrow). |
open(Joiner) / open(Joiner, configFunction) |
Opens a scope with a chosen joiner and configuration (name, thread factory, timeout). |
scope.fork(Callable) |
Starts a subtask in a new virtual thread and returns a Subtask. |
scope.join() |
Waits for the subtasks as the joiner decides; returns the joiner's result. Throws InterruptedException, a FailedException or a TimeoutException. |
scope.close() |
Cancels unfinished subtasks and waits for them. Called by try-with-resources. |
Subtask.get(), state(), exception() |
Result, SUCCESS/FAILED/UNAVAILABLE state, or the thrown exception. |
Joiner.allSuccessfulOrThrow() |
Returns the list of results; fails fast on the first exception. |
Joiner.anySuccessfulResultOrThrow() |
Returns the first successful result. |
Joiner.awaitAll() / awaitAllSuccessfulOrThrow() |
Waits for everything; the second also throws on failure. |
Try it
These two examples show what a scope gives you using only stable APIs. Calling invokeAll on a virtual-thread executor is a "wait for all" scope; invokeAny is a "first success wins" scope.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Usage notes
- Preview status: in Java 25
StructuredTaskScopeis a preview API. It has changed between releases (Java 21 to 25 renamed and replacedShutdownOnFailure/ShutdownOnSuccesswith joiners), so avoid it in code that must survive upgrades unless you accept that. - Always use try-with-resources. A scope must be closed; forgetting to call
join()beforeclose()makesclose()throwIllegalStateException. Subtask.get()beforejoin()throwsIllegalStateException; results are only defined after the scope has been joined.- Ownership: only the thread that opened the scope may fork, join and close it. Subtasks inherit scoped values from the scope owner.
- Cancellation is interruption. Subtasks must respond to
Thread.interrupt()(blocking calls do) for fail-fast and first-wins to actually free resources. - Virtual threads: each
forkcreates a virtual thread by default, which is why one thread per subtask is cheap. - Without preview:
invokeAll,invokeAny,CompletableFutureand a virtual-thread executor give most of the behavior, but they do not link the lifetime of tasks to a code block or cancel siblings for you. - Thread dumps (
jcmd <pid> Thread.dump_to_file -format=json) show the scope tree for scopes in use.