Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Concurrency

The ForkJoinPool class

Reference for ForkJoinPool, RecursiveTask and RecursiveAction: divide-and-conquer parallelism, work stealing, the common pool and choosing a threshold.

The fork/join framework runs divide-and-conquer algorithms in parallel. A task splits its work into smaller subtasks, runs them concurrently (fork()), waits for them (join()), and combines the results. A ForkJoinPool runs these tasks on a small set of worker threads using work stealing: an idle worker takes queued subtasks from a busy worker, so the CPUs stay busy even when the split is uneven.

You write a subclass of RecursiveTask<V> (returns a result) or RecursiveAction (does not), implement compute(), and submit the root task to a pool. Parallel streams and CompletableFuture.supplyAsync use the shared common pool (ForkJoinPool.commonPool()) internally.

Java
class SumTask extends RecursiveTask<Long> {
    protected Long compute() {
        // small enough? compute directly; otherwise split, fork one half, compute the other, join
    }
}
long total = new ForkJoinPool().invoke(new SumTask(...));

Try it

Java Summing an array with RecursiveTask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java RecursiveAction, invokeAll and the common pool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public class ForkJoinPool extends AbstractExecutorService
public abstract class RecursiveTask<V> extends ForkJoinTask<V> { protected abstract V compute(); }
public abstract class RecursiveAction extends ForkJoinTask<Void> { protected abstract void compute(); }
Member Description
new ForkJoinPool() / new ForkJoinPool(int parallelism) Creates a pool; the default parallelism is the number of available processors.
ForkJoinPool.commonPool() The shared static pool used by parallel streams and many async APIs. Do not shut it down.
invoke(ForkJoinTask<T>) Runs the task and waits for its result.
submit(ForkJoinTask<T>) / execute(...) Asynchronous submission; submit returns the task.
task.fork() Schedules the subtask asynchronously in the current pool (inside compute()).
task.join() / task.get() Waits for the result; join throws unchecked exceptions, get throws checked ones.
invokeAll(task1, task2) Runs two or more subtasks and waits for all of them.
getParallelism(), getPoolSize(), getStealCount() Monitoring.

Usage notes

  • Fork one half, compute the other. Calling fork() on both halves and then join() works but wastes the current thread. The pattern left.fork(); right.compute(); left.join() is the usual one.
  • Pick a sensible threshold. Too small and the overhead of creating tasks beats the gain; too large and cores sit idle. Thousands of simple operations per leaf is a common starting point; measure.
  • Tasks should be CPU-bound and independent. They must not block on I/O, locks held by other tasks, or sleep; the pool has only a few threads. Use ManagedBlocker if blocking is unavoidable.
  • Avoid shared mutable state. Return results and combine them, as in SumTask, instead of updating a shared counter.
  • Don't reuse a task object after it completed; create new instances for new work.
  • Exceptions propagate from join() to the parent task and finally to the caller of invoke.
  • Common pool caveat. On a one-CPU machine the common pool may run with parallelism 1 (or 0, meaning tasks run in the calling thread or a fresh thread, depending on the API); results stay correct, only the speedup disappears.
  • Since Java 8 for commonPool(); ForkJoinPool itself exists since Java 7.