The Fork/Join framework

Fork/Join runs divide-and-conquer algorithms in parallel: a task splits itself into smaller tasks until they are small enough to compute directly, then combines the results, while idle threads steal waiting tasks from busy ones. This page explains how work stealing works, then sums an array, measures how the split size affects speed, balances very uneven work, and shows that parallel streams run on the same pool.

Contents

How Fork/Join and work stealing work

The Fork/Join framework (Java 7, from JSR 166y) is built for one shape of problem: a task that can be split into independent halves, each of which can be split again, until the pieces are small enough to solve directly. Summing an array, sorting, searching a tree and processing images all fit. The results of the halves are then combined on the way back up.

A ForkJoinPool differs from an ordinary thread pool in how it queues work. Every worker thread owns a double-ended queue (a deque) of tasks:

  • fork() pushes a subtask onto the end of the current worker's own deque. That is a cheap, uncontended operation.
  • A worker takes its next task from the same end it pushes to (last in, first out), so it keeps working on the most recently split, smallest pieces, whose data is still in its CPU cache.
  • A worker whose deque is empty steals from the other end of another worker's deque (first in, first out). The oldest task there is the biggest piece, so one steal moves a lot of work and steals stay rare.
  • join() waits for a subtask's result, but a worker that joins does not just sleep: if the subtask has not started, it runs it itself, and otherwise it looks for other work to do meanwhile.

Java 8 added the shared ForkJoinPool.commonPool(), which parallel streams, Arrays.parallelSort and the default CompletableFuture async methods use. Its parallelism defaults to the number of cores minus one, because the thread that starts the work usually takes part too.

The ForkJoinTask types
ClassSinceReturnsBest for
RecursiveTask<V>Java 7A value from compute()Sums, counts, searches: anything combined on the way up
RecursiveActionJava 7NothingWork done in place, such as transforming or sorting an array
CountedCompleter<T>Java 8Optional value, triggered when children finishLibrary code that must avoid blocking joins; the parallel streams use it

The examples were run on JDK 21 on a 2-CPU machine, so parallel speed-ups are at most about two times.

A RecursiveTask: summing an array

Two million numbers, each i % 100, are summed by splitting the range in half until a piece has at most 10,000 elements. The expected sum is easy to check with a plain loop: 20,000 repetitions of 0 + 1 + ... + 99 = 99,000,000.

Java
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicInteger;

public class SumTask extends RecursiveTask<Long> {

    static final int THRESHOLD = 10000;
    static final AtomicInteger LEAVES = new AtomicInteger();
    static final AtomicInteger SPLITS = new AtomicInteger();
    static final Set<String> THREADS = ConcurrentHashMap.newKeySet();
    private final long[] data;
    private final int from;
    private final int to;

    SumTask(long[] data, int from, int to) {
        this.data = data;
        this.from = from;
        this.to = to;
    }

    @Override
    protected Long compute() {
        THREADS.add(Thread.currentThread().getName());
        if (to - from <= THRESHOLD) {               // small enough: do it directly
            LEAVES.incrementAndGet();
            long sum = 0;
            for (int i = from; i < to; i++) {
                sum += data[i];
            }
            return sum;
        }
        SPLITS.incrementAndGet();
        int mid = (from + to) >>> 1;                // otherwise split in two
        SumTask left = new SumTask(data, from, mid);
        SumTask right = new SumTask(data, mid, to);
        left.fork();                                // push left onto this worker's deque
        long rightSum = right.compute();            // do right in this thread
        return left.join() + rightSum;              // then wait for (or run) left
    }

    public static void main(String[] args) {
        long[] data = new long[2000000];
        for (int i = 0; i < data.length; i++) {
            data[i] = i % 100;
        }
        long check = 0;
        for (long v : data) {
            check += v;
        }
        try (ForkJoinPool pool = new ForkJoinPool(2)) {   // ForkJoinPool.close(): Java 19
            long result = pool.invoke(new SumTask(data, 0, data.length));
            System.out.println("fork/join sum: " + result + ", loop sum: " + check);
            System.out.println("splits: " + SPLITS.get() + ", leaf tasks: " + LEAVES.get()
                    + " of " + data.length / LEAVES.get() + " elements (rounded down)");
            System.out.println("worker threads that ran tasks: " + THREADS.size());
            System.out.println("pool parallelism: " + pool.getParallelism());
        }
    }
}

Output:

Output
fork/join sum: 99000000, loop sum: 99000000
splits: 255, leaf tasks: 256 of 7812 elements (rounded down)
worker threads that ran tasks: 2
pool parallelism: 2
  • The fork/join sum matches the loop. Halving 2,000,000 eight times gives 256 pieces of about 7,812 elements, the first size below the 10,000 threshold, and 255 splits produced them: a binary tree with 256 leaves has 255 inner nodes.
  • The core of every fork/join task is the last three lines of compute: fork one half, compute the other half in the current thread, then join the forked half. Computing one half directly saves a task and keeps the current thread busy instead of waiting.
  • Both workers of the 2-thread pool ran tasks. Each compute call reads only its own range and returns its own result, so the tasks share no mutable state and need no locks; the counters here exist only for the demonstration.
  • ForkJoinPool implements AutoCloseable since Java 19. Its close() waits for submitted tasks, except on the common pool, which cannot be shut down.

Choosing the threshold

The threshold decides how small a piece must be before it is computed directly. Too large, and there are too few pieces to keep all cores busy. Too small, and creating, pushing and joining tasks costs more than the work. Counting primes below 3,000,000 is a good test, because large numbers take longer to test than small ones, so equal-sized halves are not equal work.

Java
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ThresholdSpeed {

    static boolean isPrime(int n) {
        if (n < 2) {
            return false;
        }
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) {
                return false;
            }
        }
        return true;
    }

    static int countPrimes(int from, int to) {
        int c = 0;
        for (int n = from; n < to; n++) {
            if (isPrime(n)) {
                c++;
            }
        }
        return c;
    }

    static class Count extends RecursiveTask<Integer> {
        final int from;
        final int to;
        final int threshold;

        Count(int from, int to, int threshold) {
            this.from = from;
            this.to = to;
            this.threshold = threshold;
        }

        @Override
        protected Integer compute() {
            if (to - from <= threshold) {
                return countPrimes(from, to);
            }
            int mid = (from + to) >>> 1;
            Count left = new Count(from, mid, threshold);
            left.fork();
            int right = new Count(mid, to, threshold).compute();
            return left.join() + right;
        }
    }

    public static void main(String[] args) {
        int n = 3000000;
        System.out.printf("count primes below %,d on 2 cores, best of 3%n", n);
        long seq = best(() -> countPrimes(0, n));
        System.out.printf("%-24s %,5d ms%n", "plain loop", seq / 1000000);
        try (ForkJoinPool pool = new ForkJoinPool(2)) {
            for (int threshold : new int[] {10, 1000, 100000, 1500000}) {
                long t = best(() -> pool.invoke(new Count(0, n, threshold)));
                System.out.printf("threshold %,-14d %,5d ms  (%,d leaf tasks)%n",
                        threshold, t / 1000000, leaves(n, threshold));
            }
        }
        System.out.println("primes found: " + countPrimes(0, n));
    }

    static long leaves(int n, int threshold) {
        long leaves = 1;
        int size = n;
        while (size > threshold) {
            size = (size + 1) / 2;
            leaves *= 2;
        }
        return leaves;
    }

    interface Job {
        int run();
    }

    static long best(Job job) {
        long best = Long.MAX_VALUE;
        for (int i = 0; i < 3; i++) {
            long t0 = System.nanoTime();
            job.run();
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best;
    }
}

Output (2-CPU Linux machine, JDK 21; best of 3, a rough comparison):

Output
count primes below 3,000,000 on 2 cores, best of 3
plain loop                 499 ms
threshold 10               265 ms  (524,288 leaf tasks)
threshold 1,000            252 ms  (4,096 leaf tasks)
threshold 100,000          260 ms  (32 leaf tasks)
threshold 1,500,000        312 ms  (2 leaf tasks)
primes found: 216816
  • With a threshold of 1,500,000 there are only 2 leaves: one per core. It was faster than the plain loop, but far from twice as fast, because the upper half of the range holds the more expensive numbers. One core finished early and had nothing left to steal.
  • Thresholds of 1,000 and 100,000 were the fastest, close to half the loop's time. With dozens or thousands of pieces, a worker that finishes early steals another piece, and the uneven costs even out.
  • A threshold of 10 created over half a million tasks and was slightly slower than 1,000. Here each prime test is expensive, so the overhead stayed small; with cheaper work per element, such as plain addition, tiny tasks can make fork/join slower than a loop.
  • A common rule of thumb from the ForkJoinTask Javadoc is that a leaf should perform roughly 100 to 10,000 basic computational steps. Aim for at least a few times more leaves than cores, and measure.

Work stealing with very uneven tasks

Here the leaves have wildly different costs on purpose: leaf i sleeps i milliseconds, from 0 to 63 ms, 2,016 ms of work in total. A pool of 4 workers should finish in about a quarter of that if the work is spread evenly. A RecursiveAction is enough, because nothing is returned.

Java
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.atomic.AtomicLong;

public class WorkStealing {

    // Leaves have very uneven cost: leaf i sleeps i ms, so a static split would be unfair
    static final Map<String, AtomicLong> WORK_MS = new ConcurrentHashMap<>();

    static class Job extends RecursiveAction {
        final int from;
        final int to;

        Job(int from, int to) {
            this.from = from;
            this.to = to;
        }

        @Override
        protected void compute() {
            if (to - from == 1) {
                sleep(from);
                WORK_MS.computeIfAbsent(Thread.currentThread().getName(),
                        k -> new AtomicLong()).addAndGet(from);
                return;
            }
            int mid = (from + to) >>> 1;
            invokeAll(new Job(from, mid), new Job(mid, to));   // fork one, run the other
        }
    }

    public static void main(String[] args) {
        try (ForkJoinPool pool = new ForkJoinPool(4)) {
            long t0 = System.nanoTime();
            pool.invoke(new Job(0, 64));                       // 0 + 1 + ... + 63 = 2016 ms
            long ms = (System.nanoTime() - t0) / 1000000;
            long total = WORK_MS.values().stream().mapToLong(AtomicLong::get).sum();
            System.out.println("total work: " + total + " ms on 4 workers, ideal "
                    + total / 4 + " ms");
            System.out.println("wall time within 15% of ideal: " + (ms < total / 4 * 1.15));
            System.out.println("steals happened: " + (pool.getStealCount() > 0));
            Map<String, Long> share = new TreeMap<>();
            WORK_MS.forEach((k, v) -> share.put(k.replaceAll(".*-", "worker-"), v.get()));
            long min = share.values().stream().mapToLong(Long::longValue).min().orElse(0);
            long max = share.values().stream().mapToLong(Long::longValue).max().orElse(0);
            System.out.println("workers used: " + share.size()
                    + ", busiest/least busy within 25%: " + (max <= min * 1.25));
        }
    }

    static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Output:

Output
total work: 2016 ms on 4 workers, ideal 504 ms
wall time within 15% of ideal: true
steals happened: true
workers used: 4, busiest/least busy within 25%: true
  • The wall time was within 15% of the ideal 504 ms, and the busiest and least busy workers did nearly the same amount of work. A static split into 4 equal ranges would have given the last worker the leaves 48 to 63, 888 ms of work, while the first had 120 ms.
  • getStealCount() was above zero: workers that ran out of work took tasks from the others. The exact steal count and which worker ran which leaf change from run to run, which is why the program prints checks instead.
  • invokeAll(a, b) is the shorthand for "fork one, compute the other, join". This example sleeps only to make costs visible; fork/join is meant for CPU work, and real blocking calls inside it waste a worker.

Parallel streams use the same pool

A parallel stream splits its source with a Spliterator and runs the pieces as fork/join tasks on the common pool. The program counts the same primes sequentially, in parallel, and in parallel from inside a separate pool, and records which threads did the work.

Java
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;

public class ParallelStreams {

    static boolean isPrime(long n) {
        if (n < 2) {
            return false;
        }
        for (long d = 2; d * d <= n; d++) {
            if (n % d == 0) {
                return false;
            }
        }
        return true;
    }

    static long count(boolean parallel, Set<String> threads) {
        LongStream s = LongStream.range(0, 3000000);
        if (parallel) {
            s = s.parallel();
        }
        return s.peek(n -> threads.add(Thread.currentThread().getName().replaceAll("\\d+$", "N")))
                .filter(ParallelStreams::isPrime)
                .count();
    }

    public static void main(String[] args) throws Exception {
        System.out.println("cores " + Runtime.getRuntime().availableProcessors()
                + ", commonPool parallelism " + ForkJoinPool.getCommonPoolParallelism());
        Set<String> seqThreads = ConcurrentHashMap.newKeySet();
        Set<String> parThreads = ConcurrentHashMap.newKeySet();
        long seqMs = best(() -> count(false, seqThreads));
        long parMs = best(() -> count(true, parThreads));
        System.out.println("sequential: " + count(false, seqThreads) + " primes, threads "
                + new TreeSet<>(seqThreads));
        System.out.println("parallel:   " + count(true, parThreads) + " primes, threads "
                + new TreeSet<>(parThreads));
        System.out.printf("parallel time / sequential time: %.1f%n", (double) parMs / seqMs);

        // Running the stream from inside another pool makes it use that pool's workers
        // (observed behaviour of the JDK, not a documented guarantee)
        Set<String> custom = ConcurrentHashMap.newKeySet();
        try (ForkJoinPool pool = new ForkJoinPool(2)) {
            long c = pool.submit(() -> count(true, custom)).get();
            System.out.println("in a ForkJoinPool(2): " + c + " primes, threads "
                    + new TreeSet<>(custom));
        }
    }

    interface Job {
        long run() throws Exception;
    }

    static long best(Job job) throws Exception {
        long best = Long.MAX_VALUE;
        for (int i = 0; i < 3; i++) {
            long t0 = System.nanoTime();
            job.run();
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best;
    }
}

Output (2-CPU Linux machine, JDK 21; the time ratio varies between runs):

Output
cores 2, commonPool parallelism 1
sequential: 216816 primes, threads [main]
parallel:   216816 primes, threads [ForkJoinPool.commonPool-worker-N, main]
parallel time / sequential time: 0.6
in a ForkJoinPool(2): 216816 primes, threads [ForkJoinPool-1-worker-N]
  • On 2 cores the common pool has parallelism 1, yet the parallel stream used 2 threads: one common pool worker and main. The calling thread takes part in the work, which is why the pool is sized at cores minus one. The parallel run took about 0.6 of the sequential time.
  • Every parallel stream in the JVM shares the common pool, so one slow or blocking stream slows them all down. Its size can be changed with the system property java.util.concurrent.ForkJoinPool.common.parallelism.
  • Started from inside a ForkJoinPool(2), the stream ran on that pool's workers instead. Many projects use this to isolate a heavy stream, but it is observed JDK behaviour, not part of the stream specification.
  • Parallel streams pay off for large, easily split sources (arrays, ArrayList, ranges) and CPU-heavy operations. For small collections, LinkedList, I/O or operations with side effects, stay sequential. See advanced streams.

Fork/join pitfalls

The framework is simple to use and easy to use badly. These are the mistakes that most often make fork/join code slow or wrong:

  • Forking both halves and then joining them, as in left.fork(); right.fork(); left.join(); right.join();, creates an extra task per split and leaves the current thread idle in a join. Compute one half directly, or use invokeAll.
  • Joining in the wrong order: after a.fork(); b.fork();, join b first. The worker's deque is last in, first out, so the most recently forked task is the one it can most likely run itself.
  • Blocking inside a task, on I/O, locks or Thread.sleep, takes a worker away from the pool. The pool does not add a replacement unless the code uses ForkJoinPool.managedBlock. Send blocking work to a separate executor or to virtual threads.
  • Shared mutable state between tasks, such as appending to one ArrayList, is a data race. Return results up the tree instead, as RecursiveTask does.
  • Calling invoke or join on a fork/join task from inside a CompletableFuture stage or a parallel stream on the same pool can leave every worker waiting. Keep one level of parallelism per pool.

Choosing a parallel approach

When Fork/Join fits
SituationUse
Process a large array or range with a simple pipelineA parallel stream
Sort a large arrayArrays.parallelSort, which is a fork/join merge sort
Recursive divide-and-conquer with a resultRecursiveTask in a ForkJoinPool
Recursive work done in placeRecursiveAction
Isolate heavy CPU work from the rest of the JVMA dedicated new ForkJoinPool(n)
Independent tasks of similar sizeA fixed ExecutorService
Tasks that wait on I/OVirtual threads, not fork/join
Asynchronous pipelinesCompletableFuture with an explicit executor

For sizing thread pools in general, see ThreadPoolExecutor.