skip to content

How does cancellation and error propagation work across the parent/child boundary in a StructuredTaskScope, and what must a subtask do to be cancellable?

level: seniorimportance: should knowfreq 45%

answer

  1. errors UP at join(), cancellation DOWN
  2. interrupt = flag plus wake-up, never a kill
  3. interruptible blocking calls wake and throw
  4. CPU loops must poll isInterrupted()
  5. never swallow InterruptedException — restore flag or rethrow

basics

~20 s

Errors flow up: a failing subtask can cancel the scope and surface to the parent at join(). Cancellation flows down: cancelling interrupts the children. Interruption is cooperative, so a subtask stops only if it blocks interruptibly or checks the interrupt flag.

solid answer

~50 s

Propagation is bidirectional across the scope's parent/child boundary. Upward (errors): when a subtask fails, the policy may cancel the scope, and the failure reaches the owner at join() — as ExecutionException at JDK 27, FailedException at JDK 25, or via throwIfFailed() in JDK 21 to 24 — instead of being swallowed in a Future. Downward (cancellation): the scope is cancelled by its policy, by an expired timeout, or by closing it, including after the owner is interrupted and join() throws; cancelling interrupts every still-running subtask. Interruption is cooperative: it wakes a thread blocked in an interruptible call, which then throws, but never stops code that ignores it. So a subtask is cancellable if it blocks in interruptible calls (sleep, queue waits, lockInterruptibly(), socket reads on a virtual thread) and polls Thread.currentThread().isInterrupted() in CPU-bound loops. Swallowing InterruptedException or blocking uninterruptibly delays close(), which always waits for every subtask.

code

java · 13 lines
java
// A cancellable subtask: it stops promptly when the scope cancels it
Subtask<Long> total = scope.fork(() -> {
    long sum = 0;
    while (hasWork()) {
        if (Thread.currentThread().isInterrupted()) {   // CPU-bound part: poll the flag
            throw new InterruptedException("cancelled");
        }
        sum += crunch();
    }
    return sum;
});
Subtask<String> next = scope.fork(() -> queue.take());  // blocking part: take() throws
                                                         // InterruptedException on cancel

go deeper

for a junior

Knows errors go up to the parent and cancellation goes down to children, and that interruption isn't a hard kill.

for a middle

Explains cooperative interruption: interruptible blocking calls throw, loops must poll, and InterruptedException must not be swallowed.

for a senior

Details what cancels a scope (policy, timeout, closing after an interrupted join), how join() surfaces errors (throwIfFailed() before JDK 25), which operations are or aren't interruptible, and how swallowing delays close().

for a principal

Reasons about cancellation latency, uninterruptible native/blocking calls, writing robust cancellable subtasks, and how this cooperative model is consistent across Java's concurrency APIs.

## The parent/child boundary A scope creates a **parent** (the owner thread running the block) and **children** (the forked subtasks). Two kinds of signal cross this boundary, in opposite directions. ### Upward: error propagation Without structured concurrency, a failed `Future` sits silently until someone calls `get()`. With a scope, a subtask failure is **delivered to the owner**: - The completion policy decides what a failure means (e.g. the default fail-fast policy of `open()` cancels everything). - The owner learns about it at **`join()`**, which throws `ExecutionException` with the failure as its cause at JDK 27 (`FailedException` at JDK 25 and 26; in JDK 21 to 24, `throwIfFailed()` re-threw it after `join()`). - Net effect: the exception surfaces in the **enclosing block**, where ordinary `try/catch` handles it — exactly like a sequential call. Errors don't get lost. ### Downward: cancellation propagation **Cancellation** travels from parent to children. The scope is cancelled when: 1. its **policy** decides to stop early (first failure / first success), 2. a **timeout** set with `Configuration.withTimeout` expires, or 3. the scope is **closed** — including when the **owner thread itself is interrupted**: `join()` throws `InterruptedException`, try-with-resources closes the scope, and the whole subtree is cancelled. (JDK 21 to 24 also had a public `shutdown()` method; JDK 25 removed it.) Cancelling **interrupts every still-running subtask**. That brings us to the key concept. ## Java interruption is cooperative, not preemptive This is the heart of the question. **Interrupting** a thread in Java does **not** forcibly stop it. `Thread.interrupt()` sets the thread's **interrupt status**, and if the thread is blocked in an interruptible operation — `sleep`, `wait`, `join`, an `InterruptibleChannel`, a `Selector` — it also wakes the thread so that operation throws or returns. A thread running ordinary code that never checks the flag simply keeps running. (The forcible `Thread.stop()` has thrown `UnsupportedOperationException` since JDK 20 and was removed in JDK 26, because killing a thread mid-operation corrupts state.) So "cancellation propagates to children" really means "children are interrupted." Whether they *actually stop* depends on how they're written. ## How a subtask becomes cancellable A subtask is **cancellable** only if it **responds to interruption**: 1. **Blocking JDK calls react automatically.** Most blocking operations wake up when interrupted: `Thread.sleep`, `Object.wait`, `BlockingQueue.take/put`, `Lock.lockInterruptibly` and `Future.get` throw **`InterruptedException`**; I/O on an **interruptible channel** (NIO) closes the channel and throws `ClosedByInterruptException`; and on a **virtual thread**, the default for subtasks, a `java.net.Socket` read closes the socket and throws `SocketException`. If your subtask spends its time in such calls, it will unwind quickly when the scope is cancelled. 2. **CPU-bound loops must poll.** A tight computation that never blocks won't see an interrupt unless it checks: ```java while (moreWork()) { if (Thread.currentThread().isInterrupted()) return; // cooperate crunch(); } ``` 3. **Don't swallow `InterruptedException`.** Catching it and doing nothing erases the signal. The correct responses are to **propagate** it, or to **restore the flag** with `Thread.currentThread().interrupt()` and then stop: ```java try { queue.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // restore status return; // stop promptly } ``` ## What breaks cancellation - **Swallowed `InterruptedException`** (catch-and-ignore) — the classic bug. - **Uninterruptible blocking** — a native call, a `FileInputStream` read, waiting to enter a `synchronized` block, or `ReentrantLock.lock()` (as opposed to `lockInterruptibly()`). A socket read on a *platform* thread that is not backed by a channel is uninterruptible too. These won't stop on interrupt and will **delay `close()`**. - **No interrupt checks** in a long CPU loop. When subtasks ignore interruption, `close()` (which waits for all children to terminate) **can block indefinitely** — the no-orphans guarantee still holds (close *waits*), but cancellation becomes sluggish, which is its own problem. ## Putting it together - The scope (a preview API at JDK 27) is the **plumbing**: it routes failures up and cancellation down. - **Effectiveness depends on the subtasks**: they must honor interruption to be cancelled promptly. - Good subtask code: use interruptible blocking calls, poll the interrupt flag in loops, never silently swallow `InterruptedException`, and restore the flag when you can't re-throw. This cooperative model is the same one used throughout Java concurrency (ExecutorService cancellation, `Future.cancel(true)`); structured concurrency inherits it.

  • Why does interrupting a subtask not always stop it immediately?
    Because Java interruption is cooperative: interrupt() sets the status flag and wakes the thread only if it is blocked in an interruptible operation, which then throws. A thread running code that never checks the flag, or blocked uninterruptibly (a native call, entering a synchronized block, ReentrantLock.lock()), keeps going.
  • What's the correct way to handle InterruptedException in a subtask you can't propagate it from?
    Restore the interrupt status with Thread.currentThread().interrupt() and then stop the work (return/break), so callers can still observe that interruption occurred.

  • Saying cancellation forcibly kills subtask threads (preemptive) — interruption is cooperative.
  • Catching InterruptedException and ignoring it (loses the cancellation signal).
  • Assuming a tight CPU loop will be cancelled without checking the interrupt flag.
  • Believing failures are swallowed like with raw Futures — the scope surfaces them to the parent.
  • Thinking waiting to enter a synchronized block or ReentrantLock.lock() is interruptible (neither is).

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 failures reach the owner as ExecutionException from join() (FailedException at JDK 25; throwIfFailed() in JDK 21 to 24). Thread interruption itself works the same on JDK 25 and 27.

context