00:00

ForkJoinPool in Java: Divide-and-Conquer and Work-Stealing

Last updated:

ForkJoinPool is an executor built for tasks that split themselves into smaller tasks. Its threads use work-stealing: an idle thread takes queued work from a busy one, which keeps every core occupied during recursive, divide-and-conquer computations.

This tutorial covers how ForkJoinPool runs RecursiveTask and RecursiveAction, the shared common pool, and the scheduling and timeout methods added in Java 25.

1. What Is ForkJoinPool?

It is a class in java.util.concurrent, added in Java 7, that extends AbstractExecutorService. Its main job is running ForkJoinTasks, usually subclasses of RecursiveTask (returns a value) or RecursiveAction (returns nothing).

ForkJoinPool.commonPool() returns a shared, JVM-wide instance. Any ForkJoinTask that is not submitted to a specific pool runs there. The common pool never terminates until the program shuts down, so you never need to close it.

2. ForkJoinPool Hierarchy

ForkJoinPool hierarchyForkJoinPool extends AbstractExecutorService and, since Java 25, implements ScheduledExecutorService. It runs ForkJoinTask objects; RecursiveTask and RecursiveAction extend ForkJoinTask.«abstract class»AbstractExecutorServicesubmit(…), invokeAll(…)«interface»ScheduledExecutorServiceschedule(…)scheduleAtFixedRate(…)«class»ForkJoinPoolthis pageinvoke(ForkJoinTask)commonPool() «static»schedule(…), submitWithTimeout(…) †† added in Java 25«abstract class»ForkJoinTask<V>fork(), join(), invoke()«abstract class»RecursiveTask<V>compute() : V«abstract class»RecursiveActioncompute() : voidrunsextendsimplementsuses / createsinterfaceabstract classclass

Swipe sideways to see the whole diagram.

  • AbstractExecutorService (abstract class): Supplies the standard ExecutorService plumbing.
  • ScheduledExecutorService (interface): Implemented since Java 25, adding schedule() and periodic execution.
  • ForkJoinTask (abstract class): The task type the pool is optimised for, with fork() and join().
  • RecursiveTask and RecursiveAction (abstract classes): Override compute(); the first returns a result, the second does not.

3. How Fork/Join Works

  1. A task checks whether its piece of work is small enough to do directly.
  2. If not, it splits the work, calls fork() on one part so that it can run asynchronously, and computes the other part itself.
  3. join() then waits for the forked part and combines both results.
  4. Each worker keeps its own deque of tasks. Idle workers steal tasks from the others, so the load balances itself.

4. Example: Summing a Million Sales Records

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

// Divide-and-conquer sum of one million daily sales amounts (in cents)
public class SalesTotalTask extends RecursiveTask<Long> {

    private static final long serialVersionUID = 1L;
    private static final int THRESHOLD = 10_000;   // below this, just loop
    private final int[] cents;
    private final int from;
    private final int to;

    SalesTotalTask(int[] cents, int from, int to) {
        this.cents = cents;
        this.from = from;
        this.to = to;
    }

    @Override
    protected Long compute() {
        if (to - from <= THRESHOLD) {
            long sum = 0;
            for (int i = from; i < to; i++) {
                sum += cents[i];
            }
            return sum;
        }
        int mid = (from + to) >>> 1;
        SalesTotalTask left = new SalesTotalTask(cents, from, mid);
        SalesTotalTask right = new SalesTotalTask(cents, mid, to);
        left.fork();                          // run the left half asynchronously
        long rightSum = right.compute();      // work on the right half in this thread
        return left.join() + rightSum;        // wait for the left half
    }

    public static void main(String[] args) {
        int[] cents = new int[1_000_000];
        for (int i = 0; i < cents.length; i++) {
            cents[i] = 199 + (i % 50) * 10;   // predictable test data
        }

        long parallel = ForkJoinPool.commonPool().invoke(new SalesTotalTask(cents, 0, cents.length));

        long sequential = 0;
        for (int c : cents) {
            sequential += c;
        }
        System.out.println("Fork/join total : " + parallel);
        System.out.println("Sequential total: " + sequential);
        System.out.println("Results match   : " + (parallel == sequential));
    }
}
Output
Fork/join total : 444000000
Sequential total: 444000000
Results match   : true

How the code works

  1. SalesTotalTask extends RecursiveTask<Long>, so compute() returns the sum of its slice.
  2. Slices of 10,000 elements or fewer are summed with a plain loop; larger slices are split in half.
  3. The left half is forked, the right half is computed on the current thread, and left.join() collects the forked result.
  4. commonPool().invoke() runs the root task and waits for the final total, which matches the sequential loop.

5. Example: Scheduling and Timeouts (Java 25)

Since Java 25, ForkJoinPool implements ScheduledExecutorService and adds submitWithTimeout(), which cancels a task or runs a fallback action when it takes too long.

PriceLookupWithTimeout.java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

// Java 25: ForkJoinPool can schedule tasks and enforce timeouts
public class PriceLookupWithTimeout {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        try (ForkJoinPool pool = new ForkJoinPool(2)) {

            // Delayed task, as with any ScheduledExecutorService
            ScheduledFuture<String> warmUp =
                    pool.schedule(() -> "price cache warmed", 150, TimeUnit.MILLISECONDS);

            // A slow supplier call: give it 300 ms, otherwise use a cached fallback price
            ForkJoinTask<Double> price = pool.submitWithTimeout(() -> {
                Thread.sleep(2_000);                  // the supplier is far too slow
                return 21.40;
            }, 300, TimeUnit.MILLISECONDS, task -> task.complete(19.99));

            System.out.println(warmUp.get());
            System.out.println("Price used: " + price.get() + " (fallback after timeout)");
        }
    }
}
Output
price cache warmed
Price used: 19.99 (fallback after timeout)

How the code works

  1. schedule() runs the warm-up task after 150 ms and returns a ScheduledFuture.
  2. submitWithTimeout() starts the slow supplier call and arms a 300 ms timer.
  3. When the timer fires first, the action task.complete(19.99) supplies a replacement value, so get() returns the fallback.
  4. If the action were null, the task would be cancelled with cancel(true) instead.

6. Common Mistakes and Best Practices

  • Thresholds that are too small. Splitting down to tiny tasks costs more than it saves. Choose a threshold that keeps each task doing meaningful work.
  • Blocking inside fork/join tasks. Long blocking calls tie up workers that the pool expects to stay busy; use ForkJoinPool.managedBlock() or a different executor for blocking I/O.
  • Calling join() too early. Fork one half, compute the other, then join; joining immediately after forking removes the parallelism.
  • Using the common pool for everything. Many JDK features share it; create a dedicated new ForkJoinPool(n) for heavy or long-running work.
  • Closing the common pool. It cannot be shut down; only close pools you created yourself.

7. Summary

  • ForkJoinPool runs divide-and-conquer ForkJoinTasks using work-stealing threads.
  • Extend RecursiveTask or RecursiveAction and use fork(), compute() and join().
  • commonPool() is a shared pool that never terminates; create your own pool for isolated workloads.
  • Java 25 adds schedule(), periodic scheduling and submitWithTimeout().

Related Tutorials

8. References