ForkJoinPool in Java: Divide-and-Conquer and Work-Stealing
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
Swipe sideways to see the whole diagram.
AbstractExecutorService(abstract class): Supplies the standard ExecutorService plumbing.ScheduledExecutorService(interface): Implemented since Java 25, addingschedule()and periodic execution.ForkJoinTask(abstract class): The task type the pool is optimised for, withfork()andjoin().RecursiveTask and RecursiveAction(abstract classes): Overridecompute(); the first returns a result, the second does not.
3. How Fork/Join Works
- A task checks whether its piece of work is small enough to do directly.
- If not, it splits the work, calls
fork()on one part so that it can run asynchronously, and computes the other part itself. join()then waits for the forked part and combines both results.- 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
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));
}
}
Fork/join total : 444000000 Sequential total: 444000000 Results match : true
How the code works
SalesTotalTaskextendsRecursiveTask<Long>, socompute()returns the sum of its slice.- Slices of 10,000 elements or fewer are summed with a plain loop; larger slices are split in half.
- The left half is forked, the right half is computed on the current thread, and
left.join()collects the forked result. 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.
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)");
}
}
}
price cache warmed Price used: 19.99 (fallback after timeout)
How the code works
schedule()runs the warm-up task after 150 ms and returns aScheduledFuture.submitWithTimeout()starts the slow supplier call and arms a 300 ms timer.- When the timer fires first, the action
task.complete(19.99)supplies a replacement value, soget()returns the fallback. - If the action were
null, the task would be cancelled withcancel(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
ForkJoinPoolruns divide-and-conquerForkJoinTasks using work-stealing threads.- Extend
RecursiveTaskorRecursiveActionand usefork(),compute()andjoin(). commonPool()is a shared pool that never terminates; create your own pool for isolated workloads.- Java 25 adds
schedule(), periodic scheduling andsubmitWithTimeout().
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. What is work-stealing in ForkJoinPool?
Each worker thread keeps its own queue of tasks. When a worker runs out of work, it takes tasks from the queues of busy workers. This keeps all threads busy when tasks create many subtasks.
Q2. What is the difference between RecursiveTask and RecursiveAction?
Both extend ForkJoinTask and implement compute(). RecursiveTask<V> returns a result of type V, while RecursiveAction returns nothing and is used for side-effect work such as sorting an array in place.
Q3. Do I need to shut down ForkJoinPool.commonPool()?
No. The common pool is shared by the whole JVM and is not terminated by shutdown() or close(). Only shut down pools that you create yourself.
Q4. What did Java 25 add to ForkJoinPool?
ForkJoinPool now implements ScheduledExecutorService, so it supports schedule(), scheduleAtFixedRate() and scheduleWithFixedDelay(). It also adds submitWithTimeout(), cancelDelayedTasksOnShutdown() and getDelayedTaskCount().
Q5. Is ForkJoinPool good for blocking I/O tasks?
Not by default. Its design assumes tasks keep the CPU busy. For many blocking tasks, a virtual-thread executor from Executors.newVirtualThreadPerTaskExecutor() is usually a better fit.