Multithreading: RecursiveTask splits work on a ForkJoinPool

A RecursiveTask divides a problem into halves, fork()s one half to run on another pool worker while computing the other half directly, then join()s the forked half to combine results. This fork/join pattern is how the ForkJoinPool parallelizes divide-and-conquer work.

Code
class SumTask extends RecursiveTask<Long> {
    private final int[] arr;
    private final int lo, hi;
    SumTask(int[] arr, int lo, int hi) { this.arr = arr; this.lo = lo; this.hi = hi; }
    protected Long compute() {
        if (hi - lo <= 2) {
            long sum = 0;
            for (int i = lo; i < hi; i++) sum += arr[i];
            return sum;
        }
        int mid = (lo + hi) / 2;
        SumTask left = new SumTask(arr, lo, mid);
        SumTask right = new SumTask(arr, mid, hi);
        left.fork();
        long rightResult = right.compute();
        long leftResult = left.join();
        return leftResult + rightResult;
    }
}
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };
ForkJoinPool pool = new ForkJoinPool(2);
long total = pool.invoke(new SumTask(numbers, 0, numbers.length));
pool.shutdown();
System.out.println("Sum via ForkJoin: " + total);
Output
Sum via ForkJoin: 36
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms