skip to content

Walk through the lifecycle of a StructuredTaskScope: what do fork(), join(), Subtask.get(), and close() each do, and in what order must they be called?

level: middleimportance: must knowfreq 62%

answer

  1. order: open -> fork -> join -> get -> close
  2. fork: non-blocking, owner thread only, returns Subtask handle
  3. join: blocks owner until all done (or policy stops early)
  4. get: only after join, only on SUCCESS, else IllegalStateException
  5. close: interrupts stragglers, waits for all = no orphans

basics

~20 s

Open the scope (usually in try-with-resources). fork() starts each subtask and returns a handle without blocking. join() waits for all subtasks to finish. After join, get() reads a successful subtask's result. close() (automatic) shuts the scope and waits for everything to stop.

solid answer

~50 s

The lifecycle is open, fork, join, read, close. You open the scope with StructuredTaskScope.open() (a preview API at JDK 27), typically inside try-with-resources so close() always runs. Each fork(Callable) submits a subtask onto a new (virtual) thread and immediately returns a Subtask handle; it never blocks the caller, so multiple forks run concurrently. fork() must be called from the scope's owner thread. join() blocks the owner until every forked subtask has completed, or until the scope's policy decides to stop early; it must be called before you read any result. After a successful join, Subtask.get() returns the value of a subtask whose state is SUCCESS — calling get() before join, or on a failed/unavailable subtask, throws IllegalStateException. Finally close() (run automatically by try-with-resources on any exit path) cancels the scope, interrupts any still-running subtasks, and blocks until they all terminate, enforcing that nothing leaks.

code

java · 8 lines
java
try (var scope = StructuredTaskScope.open()) {
    Subtask<User>  user  = scope.fork(() -> fetchUser(id));   // non-blocking
    Subtask<Order> order = scope.fork(() -> fetchOrder(id));  // runs concurrently

    scope.join();   // block the owner until both succeed or one fails

    return new Response(user.get(), order.get());  // get() legal only after join, on SUCCESS
} // close() runs here on every exit path: cancels stragglers, waits, no orphans

go deeper

for a junior

Can recite open-fork-join-get-close and that fork doesn't block while join does.

for a middle

Explains each method's contract, the read-after-join rule, owner-thread restriction, and what close() guarantees.

for a senior

Knows subtask states (UNAVAILABLE/SUCCESS/FAILED), the IllegalStateException guards, and how policies can unblock join early.

for a principal

Reasons about the invariants the ordering enforces and the API evolution across JDK previews when planning adoption and code reviews.

## The four operations A `StructuredTaskScope` has a well-defined lifecycle. Think of the **owner thread** as the thread that creates the scope and runs the enclosing block. ### 1. Open the scope ```java try (var scope = StructuredTaskScope.open()) { /* fork, join, read */ } ``` The `try (...)` is **try-with-resources**: any object that implements `AutoCloseable` declared there gets its `close()` called automatically when the block exits, on *every* path (normal return, exception, break). `StructuredTaskScope` is `AutoCloseable`, so this is how we guarantee cleanup. The thread that calls `open()` becomes the scope's **owner**. `StructuredTaskScope` is a preview API at JDK 27 (`--enable-preview`); JDK 21 to 24 created the scope with a constructor instead. ### 2. `fork(Callable<U>)` — start a subtask ```java Subtask<User> u = scope.fork(() -> fetchUser(id)); Subtask<Order> o = scope.fork(() -> fetchOrder(id)); ``` - A **`Callable`** is a function that returns a value and may throw. - `fork` starts the callable on a **new thread** (a virtual thread by default) and returns a **`Subtask`** — a handle to that running work. - **`fork` does not block.** Control returns immediately, so the second `fork` runs concurrently with the first. - `fork` must be called by the **owner thread** only — another thread gets `WrongThreadException` — and not after `join()`, which makes it throw `IllegalStateException`. A `Subtask` has a **state**: `UNAVAILABLE` (not completed, or completed after the scope was cancelled), `SUCCESS` (completed with a value), or `FAILED` (threw). ### 3. `join()` — wait for all subtasks ```java scope.join(); ``` `join()` blocks the **owner** until **every** forked subtask has terminated — or until the scope's **policy** cancels the scope early. With the default policy of `open()`, it waits for all subtasks to succeed or any to fail, returns `null` when all succeed, and throws `ExecutionException` with the first failure as its cause (JDK 25 and 26 throw the unchecked `FailedException` instead). A scope opened with a `Joiner` can make `join()` return the results directly. `join()` may also throw `InterruptedException` (the owner was interrupted). It may be called only once to get the outcome, except that at JDK 27 a call that threw `InterruptedException` may be retried; JDK 25 rejects any second call with `IllegalStateException`. You **must** call `join()` before reading any result. A scope that forks but never joins, or reads before joining, is a programming error. ### 4. `Subtask.get()` — read a result ```java return process(u.get(), o.get()); ``` After a successful `join()`, `get()` returns the result of a subtask **whose state is `SUCCESS`**. The critical rule: **`get()` is only legal after `join()` and only on a successful subtask.** Calling it earlier, or on a `FAILED`/`UNAVAILABLE` subtask, throws `IllegalStateException` — this is deliberate, so you can't accidentally read a half-baked or failed result. (To inspect failures you use the subtask's `state()`/`exception()`, or you let the policy propagate the error — see the shutdown-policy question.) ### 5. `close()` — cancel and reap `close()` (called automatically by try-with-resources) **cancels the scope** if it is not already cancelled: it interrupts any subtask still running and **blocks until they all terminate**. This is the linchpin of the no-orphans guarantee — the block cannot finish while a child is alive. If you forked but never joined, `close()` still cancels and waits, and then throws `IllegalStateException`, so the mistake is not silent. ## The mandatory order ``` open -> fork* (owner thread, non-blocking) -> join() -> get()/read -> close() (auto) ``` Violating it is caught: read-before-join throws `IllegalStateException`; fork-from-non-owner throws `WrongThreadException`; fork-after-join and close-without-join throw `IllegalStateException`; missing close is prevented by try-with-resources. ## Why each rule exists - **fork non-blocking** → real concurrency (otherwise it'd be sequential). - **join before read** → results are actually ready and the policy has had its say. - **get only on SUCCESS** → no silent reading of failed/unfinished work. - **close waits** → the structural invariant: lifetimes nest, nothing leaks. ## Note on API evolution The surface has shifted across releases while the lifecycle stayed: the JDK 19-20 incubator's `fork` returned a `Future` read with `resultNow()`; JDK 21 introduced `Subtask` and `Subtask.get()`; JDK 25 replaced the constructors with `open(...)` factories and the shutdown subclasses with `Joiner`s; JDK 27 made `join()` throw `ExecutionException` and added a third type parameter. The *lifecycle and ordering rules* are the stable, examinable core.

  • What happens if you call Subtask.get() before join()?
    It throws IllegalStateException — get() is only valid after join() and only on a subtask whose state is SUCCESS. This guard prevents reading unfinished or failed results.
  • Does fork() block the caller?
    No. fork() starts the subtask on a new (virtual) thread and returns its Subtask handle immediately, so subsequent forks run concurrently. Blocking happens at join().

  • Believing fork() blocks until the subtask completes.
  • Calling Subtask.get() before join() (throws IllegalStateException).
  • Expecting join() on a plain open() scope to return the results — it returns null; read each Subtask.get() afterward.
  • Assuming any thread can fork into the scope — only the owner thread may fork.
  • Skipping try-with-resources and forgetting close(), risking leaked subtasks.

structured concurrency (StructuredTaskScope)
not finalpre-release 19

Assumes JDK 27, where StructuredTaskScope is a preview API (an incubator API in JDK 19 and 20) and join() throws ExecutionException; JDK 25 has the same lifecycle with FailedException instead and rejects a second join() even after an InterruptedException, and JDK 21 to 24 opened scopes with a constructor.

context