Patterncore
Fork/Join
Also called fork-join, fork/join, fork–join model, fork-join parallelism.
Fork/Join splits a task into parts that can run in parallel, and then joins them, so that only one thread continues with the combined result. Recursive splitting gives parallel divide and conquer.
- Family
- concurrency
- Intent
- Run the independent parts of a computation in parallel by forking a subtask for each part and joining all the subtasks before the computation continues.
- Also called
- Fork-join model, Fork/join framework
Intent
In the fork-join model, execution branches off in parallel at designated points in the program, and then joins at a subsequent point and resumes sequential execution.1 Parallel sections may fork recursively until a certain task granularity is reached.1
Problem
A computation has parts that do not depend on each other, such as the two halves of a sum or a sort. One thread does the parts one after the other, and the other processors stay idle. A new operating-system thread for each part costs too much, because creating new threads tends to result in too much overhead.1
Solution
Split the problem. If it is small enough, solve it directly. If not, fork a subtask for each part, join all the subtasks, and combine their results.1 By nesting fork-join computations recursively, one gets a parallel version of the divide and conquer paradigm.1
solve(1..1000000)
/ fork \
solve(left half) solve(right half) <- run in parallel
/ \ / \
... ... ... ... <- split until small
\ / \ /
\ join /
combine the sums
The primary coordination mechanisms in Java are fork(), that arranges asynchronous execution, and join(), that does not proceed until the result of the task has been computed.2 Implementations typically fork tasks or lightweight threads, not operating-system threads, and use a thread pool to execute these tasks.1 A work-stealing scheduler often maps the tasks onto the pool.1 In a ForkJoinPool, all threads attempt to find and execute tasks that were submitted to the pool or created by other active tasks.3
Example
The example sums the integers from 1 to 1,000,000. A range of at most 10,000 numbers is summed directly, and a larger range is split into two halves. The task forks the left half, solves the right half itself, and then joins the left half. The C# example gives both halves to Parallel.Invoke instead. The splits make 128 leaf ranges, and the sum matches the formula n(n+1)/2.
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
The examples for each language show the same program.
import threading
THRESHOLD = 10_000 # a range this small is summed directly
leaves = [] # one entry for each range summed directly
leaves_lock = threading.Lock()
def solve(lo, hi):
"""Return the sum of lo, lo + 1, ..., hi - 1."""
if hi - lo <= THRESHOLD:
with leaves_lock:
leaves.append(hi - lo)
return sum(range(lo, hi))
mid = (lo + hi) // 2
left = {}
# Fork: a new thread solves the left half.
t = threading.Thread(target=lambda: left.update(result=solve(lo, mid)))
t.start()
right = solve(mid, hi) # this thread solves the right half
t.join() # join: wait for the left half
return left["result"] + right
n = 1_000_000
total = solve(1, n + 1)
print("sum:", total)
print("leaf tasks:", len(leaves))
print("largest leaf, at most 10000:", max(leaves) <= THRESHOLD)
print("matches n(n+1)/2:", total == n * (n + 1) // 2)
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
- Verdict: idiom.
threading.Threadforks the left half andjoinwaits for it.
#include <algorithm>
#include <atomic>
#include <future>
#include <iostream>
const long long THRESHOLD = 10000; // a range this small is summed directly
std::atomic<int> leaves{0};
std::atomic<long long> largest{0};
// Returns the sum of lo, lo + 1, ..., hi - 1.
long long solve(long long lo, long long hi) {
if (hi - lo <= THRESHOLD) {
leaves++;
long long seen = largest.load();
while (seen < hi - lo && !largest.compare_exchange_weak(seen, hi - lo)) {
}
long long s = 0;
for (long long i = lo; i < hi; i++) s += i;
return s;
}
long long mid = (lo + hi) / 2;
// Fork: a new thread solves the left half.
std::future<long long> left = std::async(std::launch::async, solve, lo, mid);
long long right = solve(mid, hi); // this thread solves the right half
return left.get() + right; // join: wait for the left half
}
int main() {
long long n = 1000000;
long long total = solve(1, n + 1);
std::cout << "sum: " << total << "\n";
std::cout << "leaf tasks: " << leaves << "\n";
std::cout << "largest leaf, at most 10000: " << (largest <= THRESHOLD ? "True" : "False") << "\n";
std::cout << "matches n(n+1)/2: " << (total == n * (n + 1) / 2 ? "True" : "False") << "\n";
}
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
- Verdict: stdlib.
std::asyncwithstd::launch::asyncforks the left half, andgeton itsstd::futurejoins it.
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static final int THRESHOLD = 10_000; // a range this small is summed directly
static final AtomicInteger leaves = new AtomicInteger();
static final AtomicInteger largest = new AtomicInteger();
// Returns the sum of lo, lo + 1, ..., hi - 1.
static class Sum extends RecursiveTask<Long> {
final long lo, hi;
Sum(long lo, long hi) {
this.lo = lo;
this.hi = hi;
}
@Override
protected Long compute() {
if (hi - lo <= THRESHOLD) {
leaves.incrementAndGet();
largest.accumulateAndGet((int) (hi - lo), Math::max);
long s = 0;
for (long i = lo; i < hi; i++) s += i;
return s;
}
long mid = (lo + hi) / 2;
Sum left = new Sum(lo, mid);
left.fork(); // fork: the pool can run the left half on another thread
long right = new Sum(mid, hi).compute(); // this thread solves the right half
return left.join() + right; // join: wait for the left half
}
}
public static void main(String[] args) {
long n = 1_000_000;
long total = ForkJoinPool.commonPool().invoke(new Sum(1, n + 1));
System.out.println("sum: " + total);
System.out.println("leaf tasks: " + leaves.get());
System.out.println("largest leaf, at most 10000: " + (largest.get() <= THRESHOLD ? "True" : "False"));
System.out.println("matches n(n+1)/2: " + (total == n * (n + 1) / 2 ? "True" : "False"));
}
}
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
- Verdict: stdlib.
RecursiveTaskgivesforkandjoin, andForkJoinPool.commonPool()runs the tasks.
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
const long Threshold = 10_000; // a range this small is summed directly
static int leaves;
static long largest;
static readonly object gate = new object();
// Returns the sum of lo, lo + 1, ..., hi - 1.
static long Solve(long lo, long hi)
{
if (hi - lo <= Threshold)
{
Interlocked.Increment(ref leaves);
lock (gate) largest = Math.Max(largest, hi - lo);
long s = 0;
for (long i = lo; i < hi; i++) s += i;
return s;
}
long mid = (lo + hi) / 2;
long left = 0, right = 0;
// Fork both halves and join them when Parallel.Invoke returns.
Parallel.Invoke(() => left = Solve(lo, mid), () => right = Solve(mid, hi));
return left + right;
}
static void Main()
{
long n = 1_000_000;
long total = Solve(1, n + 1);
Console.WriteLine("sum: " + total);
Console.WriteLine("leaf tasks: " + leaves);
Console.WriteLine("largest leaf, at most 10000: " + (largest <= Threshold ? "True" : "False"));
Console.WriteLine("matches n(n+1)/2: " + (total == n * (n + 1) / 2 ? "True" : "False"));
}
}
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
- Verdict: stdlib.
Parallel.Invokeruns the two halves and returns when both are done.
// The tasks share one thread. Each await lets another task run.
const THRESHOLD = 10000; // a range this small is summed directly
let leaves = 0;
let largest = 0;
const tick = () => new Promise((resolve) => setImmediate(resolve));
// Returns the sum of lo, lo + 1, ..., hi - 1.
async function solve(lo, hi) {
if (hi - lo <= THRESHOLD) {
await tick();
leaves++;
largest = Math.max(largest, hi - lo);
let s = 0;
for (let i = lo; i < hi; i++) s += i;
return s;
}
const mid = Math.floor((lo + hi) / 2);
const left = solve(lo, mid); // fork: start the left half
const right = await solve(mid, hi); // solve the right half
return (await left) + right; // join: wait for the left half
}
async function main() {
const n = 1000000;
const total = await solve(1, n + 1);
console.log("sum:", total);
console.log("leaf tasks:", leaves);
console.log("largest leaf, at most 10000:", largest <= THRESHOLD ? "True" : "False");
console.log("matches n(n+1)/2:", total === (n * (n + 1)) / 2 ? "True" : "False");
}
main();
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
- Verdict: idiom. The tasks share one thread, so this shows the fork and join steps with promises but not parallel speed-up.
// The tasks share one thread. Each await lets another task run.
const THRESHOLD = 10000; // a range this small is summed directly
let leaves: number = 0;
let largest: number = 0;
const tick = (): Promise<void> => new Promise<void>((resolve) => setImmediate(resolve));
// Returns the sum of lo, lo + 1, ..., hi - 1.
async function solve(lo: number, hi: number): Promise<number> {
if (hi - lo <= THRESHOLD) {
await tick();
leaves++;
largest = Math.max(largest, hi - lo);
let s = 0;
for (let i = lo; i < hi; i++) s += i;
return s;
}
const mid = Math.floor((lo + hi) / 2);
const left = solve(lo, mid); // fork: start the left half
const right = await solve(mid, hi); // solve the right half
return (await left) + right; // join: wait for the left half
}
async function main(): Promise<void> {
const n = 1000000;
const total = await solve(1, n + 1);
console.log("sum:", total);
console.log("leaf tasks:", leaves);
console.log("largest leaf, at most 10000:", largest <= THRESHOLD ? "True" : "False");
console.log("matches n(n+1)/2:", total === (n * (n + 1)) / 2 ? "True" : "False");
}
main();
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
- Verdict: idiom. The tasks share one thread, so this shows the fork and join steps with promises but not parallel speed-up.
package main
import (
"fmt"
"sync"
)
const threshold = 10_000 // a range this small is summed directly
var (
mu sync.Mutex
leaves int
largest int64
)
// solve returns the sum of lo, lo + 1, ..., hi - 1.
func solve(lo, hi int64) int64 {
if hi-lo <= threshold {
mu.Lock()
leaves++
largest = max(largest, hi-lo)
mu.Unlock()
var s int64
for i := lo; i < hi; i++ {
s += i
}
return s
}
mid := (lo + hi) / 2
var left int64
var wg sync.WaitGroup
wg.Add(1)
go func() { // fork: a new goroutine solves the left half
defer wg.Done()
left = solve(lo, mid)
}()
right := solve(mid, hi) // this goroutine solves the right half
wg.Wait() // join: wait for the left half
return left + right
}
func boolText(b bool) string {
if b {
return "True"
}
return "False"
}
func main() {
var n int64 = 1_000_000
total := solve(1, n+1)
fmt.Println("sum:", total)
fmt.Println("leaf tasks:", leaves)
fmt.Println("largest leaf, at most 10000:", boolText(largest <= threshold))
fmt.Println("matches n(n+1)/2:", boolText(total == n*(n+1)/2))
}
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
- Verdict: idiom. A goroutine solves the left half, and
sync.WaitGroupjoins it.
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::thread;
const THRESHOLD: u64 = 10_000; // a range this small is summed directly
static LEAVES: AtomicUsize = AtomicUsize::new(0);
static LARGEST: AtomicU64 = AtomicU64::new(0);
/// Returns the sum of lo, lo + 1, ..., hi - 1.
fn solve(lo: u64, hi: u64) -> u64 {
if hi - lo <= THRESHOLD {
LEAVES.fetch_add(1, Ordering::SeqCst);
LARGEST.fetch_max(hi - lo, Ordering::SeqCst);
return (lo..hi).sum();
}
let mid = (lo + hi) / 2;
thread::scope(|s| {
let left = s.spawn(|| solve(lo, mid)); // fork: a scoped thread solves the left half
let right = solve(mid, hi); // this thread solves the right half
left.join().unwrap() + right // join: wait for the left half
})
}
fn main() {
let n: u64 = 1_000_000;
let total = solve(1, n + 1);
let text = |b: bool| if b { "True" } else { "False" };
println!("sum: {}", total);
println!("leaf tasks: {}", LEAVES.load(Ordering::SeqCst));
println!("largest leaf, at most 10000: {}", text(LARGEST.load(Ordering::SeqCst) <= THRESHOLD));
println!("matches n(n+1)/2: {}", text(total == n * (n + 1) / 2));
}
sum: 500000500000
leaf tasks: 128
largest leaf, at most 10000: True
matches n(n+1)/2: True
- Verdict: stdlib.
std::thread::scopespawns a scoped thread for the left half and joins it before the scope ends.
Consequences
Benefits:
- The fork primitive lets the programmer specify potential parallelism, and the implementation then maps it onto actual parallel execution.1
- The scheduler can be much simpler than a full operating-system scheduler, because in the fork-join paradigm threads only block at the join point.1
- Huge numbers of tasks and subtasks can run on a small number of actual threads in a
ForkJoinPool.2
Liabilities:
- The task size matters. If tasks are too big, then parallelism cannot improve throughput. If they are too small, then memory and internal task maintenance overhead may overwhelm processing.2 As a very rough rule of thumb, a Java task should perform more than 100 and less than 10000 basic computational steps.2
- Tasks should avoid synchronized methods or blocks, should minimize other blocking synchronization apart from joining other tasks, and should not perform blocking I/O.2
- A plain thread pool that blocks a worker on each join can stall. A
ForkJoinPooltries to keep enough active threads even if some tasks are stalled waiting to join others, but it does not guarantee this in the face of blocked I/O or other unmanaged synchronization.3
This program forks each half into a plain pool of 2 workers and blocks the worker on the join. Both workers soon wait for subtasks that are still in the queue:
This code runs but gives a wrong answer on purpose.
from concurrent.futures import ThreadPoolExecutor, TimeoutError
pool = ThreadPoolExecutor(max_workers=2)
def solve(lo, hi):
if hi - lo <= 10_000:
return sum(range(lo, hi))
mid = (lo + hi) // 2
# Wrong: each task submits its halves to the same small pool and blocks.
left = pool.submit(solve, lo, mid)
right = pool.submit(solve, mid, hi)
return left.result(timeout=1) + right.result(timeout=1)
try:
print("sum:", pool.submit(solve, 1, 1_000_001).result())
except TimeoutError:
print("join timed out: both workers wait for subtasks that no worker can run")
pool.shutdown(cancel_futures=True)
join timed out: both workers wait for subtasks that no worker can run
When not to use it
Do not use fork/join when the parts depend on each other, or when each part waits for I/O. Subdividable tasks should ideally access variables that are completely independent of those accessed by other running tasks.2 Do not use it when the whole problem is smaller than one good leaf task, because the cost of the forks is then larger than the work.
Variants and related patterns
- Fork one part, do the other. In the parallel merge sort of CLRS, the first recursive call is forked, and the main task handles the second recursive call itself. This is intentional, because forking tasks may come at an expense. If both calls were subtasks, the main task would have no additional work to do before it is blocked at the join.1 The next program counts the threads that each way starts:
import threading
started = {"count": 0}
lock = threading.Lock()
def fork(fn, *args):
out = {}
t = threading.Thread(target=lambda: out.update(result=fn(*args)))
with lock:
started["count"] += 1
t.start()
return t, out
def solve_fork_both(lo, hi):
if hi - lo <= 10_000:
return sum(range(lo, hi))
mid = (lo + hi) // 2
(t1, a), (t2, b) = fork(solve_fork_both, lo, mid), fork(solve_fork_both, mid, hi)
t1.join() # this thread only waits
t2.join()
return a["result"] + b["result"]
def solve_fork_one(lo, hi):
if hi - lo <= 10_000:
return sum(range(lo, hi))
mid = (lo + hi) // 2
t, a = fork(solve_fork_one, lo, mid)
right = solve_fork_one(mid, hi) # this thread does the other half
t.join()
return a["result"] + right
for solve in (solve_fork_both, solve_fork_one):
started["count"] = 0
total = solve(1, 1_000_001)
print(f"{solve.__name__}: sum {total}, threads started {started['count']}")
solve_fork_both: sum 500000500000, threads started 254
solve_fork_one: sum 500000500000, threads started 127
- Join compared with a barrier. A join may look like a barrier, but after a barrier the threads continue to work, and after a join only one thread continues.1
- Scoped threads. In Rust,
std::thread::scopecreates a scope for spawning threads that can borrow non-'staticdata, because the scope guarantees that all threads are joined at the end of the scope.4 - Work stealing.
rayon::jointakes two closures and potentially runs them in parallel. The calling thread runs closure A and advertises closure B to other threads. If B has been stolen, the calling thread looks for other work while it waits for the thief to execute B.5
A thread pool runs the tasks of a fork/join framework, and a future holds the result that a join waits for.
Known uses
- Fork-join is the main model of parallel execution in OpenMP.1
- The Java concurrency framework, the Task Parallel Library for .NET and Intel Threading Building Blocks support it.1
- The Cilk language has the
spawnandsynckeywords, and Cilk Plus hascilk_spawnandcilk_sync.1 - Java has
ForkJoinPoolwith a staticcommonPool()that is appropriate for most applications.3 - The Rust library Rayon uses a fixed pool of worker threads and work stealing.5
References
- Fork–join model, Wikipedia, lead; Examples; Implementations
- Java SE 21 API, java.util.concurrent.ForkJoinTask, class description
- Java SE 21 API, java.util.concurrent.ForkJoinPool, class description
- The Rust Standard Library, std::thread::scope, function description
- Rayon documentation, rayon::join, function description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag V37PWB Edit this page History Report an error Markdown