Fork/Join Framework
Divide-and-conquer parallelism: split a task until it is small, run the halves on a work-stealing pool, and join the results; with Java's ForkJoinPool, a traced sum, and why a plain thread pool deadlocks on the same code.
Overview
Fork/join is a way to run a divide-and-conquer algorithm on every core. A task that is too big splits itself into subtasks (the fork), runs them in parallel, waits for their results (the join) and combines them. A task that is small enough just does the work in a loop.
Java ships it as ForkJoinPool with RecursiveTask and RecursiveAction. Its scheduler comes from Doug Lea's 2000 paper, which adapted the work-stealing scheduler of Cilk: each worker thread keeps its own queue of tasks, and idle workers steal from busy ones. The interview questions are about that scheduler, about choosing the size at which a task stops splitting, and about what must never happen inside a task.
Fork, compute, join
Every fork/join task has the same shape. The idiom that matters is fork one half, compute the other half in the current thread, then join the forked half. The current thread stays busy instead of forking both halves and sitting idle.
A task's compute(lo, hi) runs the same routine every time it is called.
- Test the size: is hi - lo at most the threshold?
- If it is, run a plain loop over the range and return the result.
- If it is not, fork the left half onto this worker's deque.
- Compute the right half in this thread.
- Join the left half and add the two results.
The threshold test decides between a plain loop and a split, and the current thread always keeps one half for itself. Here is a trace that sums [3, 1, 4, 1, 5, 9, 2, 6] with a threshold of 2 elements.
- Task [0, 8) is too big, so it forks [0, 4) and computes [4, 8).
- Task [4, 8) is too big, so it forks [4, 6) and computes [6, 8).
- Task [6, 8) is small: 2 + 6 = 8.
- Task [4, 8) joins [4, 6), which gives 5 + 9 = 14, and adds 8 for 22.
- Task [0, 4) is joined by [0, 8). It is too big, so it forks [0, 2) and computes [2, 4).
- Task [2, 4) is small: 4 + 1 = 5.
- Task [0, 4) joins [0, 2), which gives 3 + 1 = 4, and adds 5 for 9.
- Task [0, 8) adds 9 + 22 and returns 31.
On one worker the steps run in this order. With more workers, an idle worker steals [0, 4) at step 1 and runs steps 5 to 7 while the first worker runs steps 2 to 4. Drawn as a tree, the same run looks like this.
Interview questions
- What is the Fork/Join framework and when do you use it?
- How does work stealing work, and why do thieves take from the other end of the deque?
- What is the difference between RecursiveTask and RecursiveAction?
- Why fork one half and compute the other, instead of forking both and joining both?
- Where else is ForkJoinPool used in Java, and what can go wrong with the common pool?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio