What is structured concurrency in Java, and what problem does it solve compared to launching threads or futures manually?
answer
- Structured programming for threads: lifetimes nest in a block
- open scope -> fork subtasks -> join -> read -> close
- try-with-resources close() => no orphan can survive
- fixes leaks, swallowed errors, no cancellation propagation
- pairs with virtual threads (cheap to fork)
basics
~20 sStructured concurrency ties a group of concurrent tasks to a code block. You open a scope, start subtasks, wait for them all, then close the scope. No task can outlive the block, so you never leak forgotten threads.
solid answer
~50 sStructured concurrency treats a group of related concurrent tasks as a single unit of work bound to a syntactic block, the way structured programming bound control flow to blocks. In Java (a preview API through JDK 27) you open a StructuredTaskScope with StructuredTaskScope.open() in a try-with-resources, fork() each subtask, then join() to wait for all of them before the block exits. Because the scope is closed when the block exits, no subtask can outlive its parent: there are no orphaned threads leaking past the method that started them. This fixes the classic problems of ad-hoc concurrency: a future you forgot to cancel keeps running after an error, exceptions from one task get swallowed, and thread lifetimes are unbounded and untracked. The result reads top-to-bottom like sequential code, gives you a clear parent-child relationship for error and cancellation propagation, and shows that structure in thread dumps.
go deeper
Can state the open-fork-join-close pattern and that no task outlives the block, so threads aren't leaked.
Explains the concrete problems with raw Futures (orphans, swallowed errors, no cancellation) and how the scope fixes each.
Connects it to structured programming, error/cancellation propagation semantics, and the virtual-threads pairing; knows it's a preview API.
Frames it as a concurrency discipline/architecture choice, reasons about migrating an existing Future/Executor codebase, observability, and the preview-stability trade-off for production adoption.
## The problem **Concurrency** means running more than one task at the same time. Traditionally in Java you do this by submitting work to an `ExecutorService` and getting back a `Future` (a handle to a result that isn't ready yet), or by starting raw `Thread`s. This is *unstructured*: once you submit a task, its lifetime is no longer tied to the method that started it. Several things go wrong: - **Thread/task leaks (orphans).** If your method returns or throws before a submitted task finishes, that task keeps running in the background with nobody waiting on it. It is an *orphan* — a thread that outlived the code that created it. - **Swallowed errors.** If task A fails, task B often keeps running pointlessly, and the failure may sit unnoticed inside a `Future` until someone calls `get()`. - **No cancellation propagation.** Cancelling the overall operation does not automatically cancel the in-flight subtasks. - **Hard to read.** The relationship between "the thing I'm doing" and "the helper tasks it spawned" is invisible in the code and in thread dumps. ## Structured programming, applied to threads Decades ago, *structured programming* replaced `goto` with blocks (`if`, `while`, function calls): control flow enters a block at the top and leaves at the bottom, so lifetimes nest cleanly. **Structured concurrency** applies the same principle to concurrent tasks: *if a task splits into concurrent subtasks, they must all complete (or be cancelled) before the parent block exits.* The lifetime of every subtask is **nested** inside the block that created it. ## How Java expresses it: `StructuredTaskScope` Java's API is `StructuredTaskScope` in `java.util.concurrent`: an incubator API in JDK 19 and 20 and a **preview API** from JDK 21 through 27 (JEPs 453, 462, 480, 499, 505, 525, 533), so it needs `--enable-preview`. The pattern is: ```java try (var scope = StructuredTaskScope.open()) { Subtask<String> a = scope.fork(() -> fetchUser()); // start subtask Subtask<String> b = scope.fork(() -> fetchOrder()); // start subtask scope.join(); // wait for all; throws if one failed return a.get() + b.get(); // read results } // close() here: nothing started inside is still running ``` - **`StructuredTaskScope.open()`** opens the scope, and the thread that opens it is its **owner**. (JDK 21 to 24 used a constructor, `new StructuredTaskScope<>()`, instead.) - **`fork(Callable)`** starts a *subtask* on a new thread (a virtual thread by default) and returns a `Subtask` handle. It does **not** block. - **`join()`** blocks the owner until every forked subtask has succeeded or one has failed; with the default policy of `open()` it then throws if a subtask failed. - **try-with-resources** ensures `scope.close()` runs no matter how the block exits — normal return, exception, or otherwise. `close()` is what enforces the structure: it cannot return while any subtask is still alive, so an orphan is impossible. ## Why this is better 1. **No orphans.** The block boundary plus `close()` guarantee every subtask is done before you move on. 2. **Automatic error propagation.** Under the default policy of `open()`, if one subtask throws, the scope interrupts the others and `join()` throws `ExecutionException` with that failure as the cause (`FailedException` on JDK 25 and 26; `throwIfFailed()` on a `ShutdownOnFailure` scope in JDK 21 to 24) — you don't have to poll each `Future`. 3. **Cancellation propagation.** Cancelling/interrupting the parent thread propagates down to the children. 4. **Readability and observability.** The code reads like sequential code, and tooling (thread dumps) can show the parent-child tree. ## Virtual threads connection Structured concurrency shines with **virtual threads** (lightweight threads managed by the JVM, cheap enough to have millions). Forking a subtask per unit of work is fine because virtual threads are cheap; the scope keeps their lifetimes disciplined. The two features were designed together. ## Status note `StructuredTaskScope` is a **preview API** at JDK 27, and its shape has changed between previews: JDK 25 replaced the constructors and the `ShutdownOnFailure`/`ShutdownOnSuccess` subclasses with `open(...)` factories and `Joiner` policies, and JDK 27 made `join()` throw `ExecutionException` and added a third type parameter for that exception. The *concept* — scope-bound lifetimes, fork/join, error and cancellation propagation — is stable and is what interviewers test.
- What guarantees that no subtask outlives the scope?The scope's close() (run by try-with-resources on every exit path) blocks until all forked subtasks have terminated, so the block cannot complete while a subtask is still alive.
- Why is structured concurrency a natural fit for virtual threads?Virtual threads are cheap, so forking one subtask per unit of work is affordable; the scope then keeps those many short-lived threads disciplined and observable.
- Saying fork() blocks or runs the task on the current thread — it starts a new thread and returns immediately.
- Claiming it makes code parallel/faster by itself; it structures lifetimes, the speedup comes from running tasks concurrently.
- Forgetting to call join() before reading results — Subtask.get() is illegal before join().
- Thinking it replaces ExecutorService for everything; it targets a group of subtasks scoped to one operation.
- structured concurrency (StructuredTaskScope)
- not finalpre-release 19
Assumes JDK 27, where StructuredTaskScope is a preview API (--enable-preview). JDK 25 has the same open/fork/join shape, but join() throws FailedException instead of ExecutionException; JDK 21 to 24 used a constructor and the ShutdownOnFailure and ShutdownOnSuccess subclasses.
context
- JEP 533: Structured Concurrency (Seventh Preview)openjdk.org
- StructuredTaskScope (Java SE 27 & JDK 27)docs.oracle.com