skip to content

In Java's ForkJoinTask, why is fork-one, compute-the-other, then join the idiomatic fork()/join() order, and what goes wrong with fork-both-join-both or fork-then-immediately-join?

level: middleimportance: must knowfreq 60%

answer

  1. fork = queue async; join = await + result
  2. fork-one, compute-other, join-one
  3. fork-then-immediately-join = zero parallelism
  4. fork-both-join-both = correct but wastes a fork
  5. invokeAll encapsulates the idiom; LIFO deque

basics

~20 s

fork() schedules a subtask to run asynchronously; join() waits for it and returns its result. The idiom is: fork the left subtask, run the right one yourself by calling compute() directly, then join the left. This keeps the current thread busy instead of idle, and avoids forking a task only to immediately wait on it (which gives no parallelism).

solid answer

~50 s

fork() pushes a subtask onto the current worker's deque so an idle worker can steal it; join() waits for it and returns its result, helping run other tasks meanwhile. The idiom forks one half, calls compute() directly on the other in the current thread, then joins the forked half: the current thread does useful work while its sibling may run elsewhere. If you fork() then immediately join() the same task, you get no parallelism: the join usually takes the task back off this thread's deque and runs it here (or waits, if a thief grabbed it), so the work is serial plus the fork overhead. Forking both then joining both is correct, but the second fork is wasted: the current thread could have run one half directly. When you join several, join innermost-first (most recently forked first), which the ForkJoinTask Javadoc calls likely substantially more efficient; invokeAll encodes the idiom.

go deeper

for a junior

Knows fork() runs a subtask asynchronously and join() waits for its result.

for a middle

Writes the fork-one/compute-other/join-one idiom correctly and explains why fork-then-immediate-join gives no parallelism.

for a senior

Ties the ordering to the per-worker LIFO deque and work-stealing, knows invokeAll, and reasons about join order and why the waiting worker can still help.

for a principal

Reasons about deque locality, steal contention, and when the redundant-fork pattern still pays off (e.g. highly uneven splits or external blocking), and overhead tradeoffs versus other parallel abstractions.

## The two primitives In the Fork/Join framework a task is split into subtasks, and two methods coordinate them: - **`fork()`** — pushes this task onto the **current worker thread's local deque** (double-ended queue) and returns immediately (called outside any pool, it goes to the common pool instead). The task is now *eligible to run asynchronously*: either the current thread will pop it later, or an idle worker thread will **steal** it. `fork()` does **not** start a thread for the task; it queues work for the pool, at most waking an idle worker or starting one while the pool has fewer threads than its parallelism. - **`join()`** — waits until the task has completed and returns its result (for a `RecursiveTask`). The calling worker doesn't just block uselessly: if the task is still in its own deque, it takes it back and runs it; otherwise it may help by executing other queued tasks (this is part of why Fork/Join scales). ## Why the idiom is fork-one / compute-other / join-one The recommended shape inside `compute()` is: ```java left.fork(); // 1. make left available to other workers R rightResult = right.compute(); // 2. do right myself, right now R leftResult = left.join(); // 3. collect left's result return combine(leftResult, rightResult); ``` Reasoning step by step: 1. **fork-one** publishes `left` so an *idle* worker can grab it in parallel. 2. **compute-the-other** keeps *this* thread productive: instead of forking `right` and then standing idle, the current thread directly runs `right`. One thread, two subtasks, zero idle time — and `right` runs without any queueing overhead. 3. **join-one** then waits for `left`. By the time we get here we've already finished `right`, so ideally `left` is also done (or nearly), minimizing the wait. This maximizes the ratio of useful work to coordination overhead, and it respects the deque's **LIFO** discipline: the current thread tends to pop the most-recently-pushed task, so forking only one and computing the other avoids fighting the work-stealing structure. ## What goes wrong with the anti-patterns **(a) fork() then immediately join() the same task:** ```java left.fork(); R leftResult = left.join(); // BAD: nothing else happening meanwhile R rightResult = right.compute(); ``` The current thread forks `left` and joins it at once. `left` is still on top of its own deque, so the join usually just takes it back and runs it on this thread; if an idle worker stole it in that instant, this thread waits for it instead. Either way nothing runs in parallel — you've serialized the work and *added* the cost of queueing `left`. This is strictly worse than just calling `left.compute()`. **(b) fork both, then join both:** ```java left.fork(); right.fork(); // wasteful second fork R l = left.join(); R r = right.join(); ``` This is **correct** but suboptimal. Both halves go through the deque, so you pay a second push and a later removal for a task this thread could simply have run. At the joins, the worker takes back whichever forked task is still in its own deque and runs it, and waits or helps only for one a thief took; joining `left` first means digging it out from under `right`, which costs more than a plain pop. The cleaner idiom avoids the redundant fork. **(c) Wrong join order:** If you do fork both, join **innermost-first** (`right.join()` before `left.join()` when `right` was forked last). The `ForkJoinTask` Javadoc says `a.fork(); b.fork(); b.join(); a.join();` is likely to be substantially more efficient than joining `a` first: the last-forked task sits on top of the local deque, so joining it is a cheap pop, while the first-forked one sits at the end thieves take from and has the best chance of running elsewhere meanwhile. The fork-one/compute-other idiom sidesteps this entirely. ## The convenience shortcut `invokeAll(t1, t2, ...)` forks all but the first, runs the first in the current thread, and joins the rest — encapsulating the idiom for you. If subtasks fail, it rethrows one of their exceptions and may cancel the others. Use it to avoid hand-writing the ordering. ## Key takeaways - `fork()` = queue async, `join()` = await + result. - Never `fork()` a task you'll `join()` with nothing in between. - Keep the current thread busy: compute one subtask directly. - Prefer `invokeAll` or fork-left/compute-right/join-left.

  • What does invokeAll do, and how does it relate to the idiom?
    invokeAll forks all tasks except the first, executes the first directly in the current thread, then joins the others — it bakes in the fork-one/compute-other/join idiom so you don't hand-order fork/join calls.
  • If you fork both subtasks, in what order should you join them and why?
    Join the most recently forked first (reverse of fork order), innermost-first as the ForkJoinTask Javadoc puts it. The last-forked task is on top of this thread's deque, so joining it is a cheap pop, while the first-forked one sits where thieves steal from and may already be running elsewhere by the time you join it.

  • Claiming fork() starts a new thread for the task — it queues the task on a deque for pool workers
  • fork() then immediate join() of the same task — kills parallelism
  • Joining in forward order after forking both (fights the LIFO deque)
  • Thinking join() makes the worker idle — it can help run other tasks while waiting
  • Calling compute() on a forked task (double-execution) instead of join()

ForkJoinTask fork() and join()
Java 1.7

The join mechanics described (a joining worker takes a still-queued task back off its own deque and runs it) are the JDK 27 implementation and the same at JDK 25 LTS; the idiom and the join-order advice are the public ForkJoinTask contract.

context