CodeGym /Courses /JAVA 25 SELF /ForkJoinPool and RecursiveTask: recursive tasks

ForkJoinPool and RecursiveTask: recursive tasks

JAVA 25 SELF
Level 54, Lesson 3
Available

1. ForkJoinPool: what it is and why you need it

ForkJoinPool is a specialized thread pool that implements the “divide and conquer” approach. Its job is to parallelize work as efficiently as possible when a large task can be split into a set of independent subtasks, executed in parallel, and then merged.

  • Fork (split) — the task is divided into subtasks.
  • Join (merge) — subtask results are combined into the final result.

ForkJoinPool is the heart of parallel streams in Java: when you write list.parallelStream(), it’s exactly what is used under the hood. But you can also use it directly to gain more control.

When ForkJoinPool is especially useful

ForkJoinPool shines on tasks that split easily into independent parts: for example, processing very large arrays where each chunk is processed separately and then results are combined.

  • The task is easy to split into independent subtasks: sorting, searching, summing.
  • Subtasks are roughly equal in size and do not depend on each other.
  • You need to utilize all CPU cores for maximum speed.
+---------------------+
|   Large task        |
+---------------------+
          |
          v
+---------+---------+
|  Subtask 1        |
|  Subtask 2        |
|  ...              |
+-------------------+
          |
          v
+---------+---------+
|  Results          |
+-------------------+

That’s how “divide and conquer” works: split — compute in parallel — merge.

2. RecursiveTask and RecursiveAction: two sides of the same coin

In ForkJoinPool, tasks are implemented via special classes that can split into subtasks and merge results. RecursiveTask<T> returns a result, while RecursiveAction does not. In practice, RecursiveTask is used more often to return, for example, a sum, a maximum, or a count.

To create such a task, subclass and implement the compute() method. In it you describe the logic: if the task is small — solve it immediately; if it’s large — split it into subtasks, launch them in parallel via fork(), and merge results using join(). That yields natural recursive parallelism.

3. Syntax and example: parallel computation of an array sum

Suppose we have a large array of numbers and we want to quickly compute the sum of all elements.

Step 1. Task class

import java.util.concurrent.RecursiveTask;

public class ArraySumTask extends RecursiveTask<Long> {
    private static final int THRESHOLD = 1_000; // Threshold for splitting the task
    private final int[] array;
    private final int start, end;

    public ArraySumTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        // If the task is small — compute directly
        if (end - start <= THRESHOLD) {
            long sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        } else {
            // Split the task into two subtasks
            int mid = (start + end) / 2;
            ArraySumTask leftTask = new ArraySumTask(array, start, mid);
            ArraySumTask rightTask = new ArraySumTask(array, mid, end);

            // Launch subtasks in parallel
            leftTask.fork(); // Asynchronously
            long rightResult = rightTask.compute(); // Synchronously
            long leftResult = leftTask.join(); // Wait for the left one to finish

            // Combine the result
            return leftResult + rightResult;
        }
    }
}
  • If the task is small (smaller than the THRESHOLD) — compute the sum with a regular loop.
  • If it’s large — split it in two, start one asynchronously via fork(), compute the other synchronously via compute(), then merge with join().

Step 2. Run the task via ForkJoinPool

import java.util.concurrent.ForkJoinPool;

public class ForkJoinSumDemo {
    public static void main(String[] args) {
        int[] numbers = new int[10_000_000];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = 1; // For simplicity — the sum should equal the array length
        }

        ForkJoinPool pool = new ForkJoinPool(); // By default — equals the number of cores

        ArraySumTask task = new ArraySumTask(numbers, 0, numbers.length);

        long result = pool.invoke(task); // Run the task

        System.out.println("Sum of array elements: " + result);
    }
}

How does it work?

  • ForkJoinPool decides how many threads to use (usually — the number of cores).
  • The task is automatically split into subtasks, each of which can run on a separate core.
  • Performance is usually higher than sequential code (especially on large data and multi-core systems).

4. How ForkJoinPool works: a bit under the hood

Work-stealing (stealing work)

ForkJoinPool implements “work stealing”: if a thread runs out of tasks, it “steals” work from another thread. This provides effective load balancing and keeps all cores busy.

Basic algorithm

  • The main task is split into subtasks.
  • Subtasks are placed in specialized queues.
  • Threads take tasks from their own queues, and when they are empty — they “look for” work from neighbors.
  • When everything is done, the results are merged.

Workflow diagram

flowchart TD
    A[Main task] --> B1[Subtask 1]
    A --> B2[Subtask 2]
    B1 --> C1[Small task 1]
    B1 --> C2[Small task 2]
    B2 --> C3[Small task 3]
    B2 --> C4[Small task 4]
    C1 --> D[Merge results]
    C2 --> D
    C3 --> D
    C4 --> D

5. RecursiveAction — when you don't need to return a result

If you simply need to do something in parallel and return no result, use RecursiveAction. Typical examples include parallel array filling, printing, in-place sorting, and so on.

import java.util.concurrent.RecursiveAction;

public class PrintTask extends RecursiveAction {
    private static final int THRESHOLD = 100;
    private final int[] array;
    private final int start, end;

    public PrintTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        if (end - start <= THRESHOLD) {
            for (int i = start; i < end; i++) {
                System.out.print(array[i] + " ");
            }
        } else {
            int mid = (start + end) / 2;
            invokeAll(
                new PrintTask(array, start, mid),
                new PrintTask(array, mid, end)
            );
        }
    }
}

6. Practice: parallel search for the maximum value in an array

import java.util.concurrent.RecursiveTask;

public class MaxFindTask extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 1000;
    private final int[] array;
    private final int start, end;

    public MaxFindTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (end - start <= THRESHOLD) {
            int max = array[start];
            for (int i = start + 1; i < end; i++) {
                if (array[i] > max) max = array[i];
            }
            return max;
        } else {
            int mid = (start + end) / 2;
            MaxFindTask left = new MaxFindTask(array, start, mid);
            MaxFindTask right = new MaxFindTask(array, mid, end);
            left.fork();
            int rightResult = right.compute();
            int leftResult = left.join();
            return Math.max(leftResult, rightResult);
        }
    }
}

Run:

import java.util.concurrent.ForkJoinPool;

public class ForkJoinMaxDemo {
    public static void main(String[] args) {
        int[] array = new int[5_000_000];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int)(Math.random() * 1_000_000);
        }

        ForkJoinPool pool = new ForkJoinPool();
        MaxFindTask task = new MaxFindTask(array, 0, array.length);

        int max = pool.invoke(task);

        System.out.println("Maximum value: " + max);
    }
}

7. Advantages and limitations of ForkJoinPool

Advantages

  • Automatic load balancing. Work-stealing makes it possible to use all cores efficiently.
  • Convenience. No need to create and manage threads manually.
  • High performance. Especially on large tasks and multi-core systems.
  • Flexibility. You can split tasks into as many parts as needed.

Limitations

  • Strong coupling between subtasks. If subtasks wait on each other frequently, the benefit diminishes.
  • Tasks that are too fine-grained. The overhead of splitting/synchronization can eat up the advantage.
  • Side effects. You must not modify shared variables without synchronization — you will get a race condition.
  • Applicability. Best for tasks that can be split into independent parts.

8. Common mistakes when working with ForkJoinPool and RecursiveTask

Error #1: Over-splitting the task. If the threshold (THRESHOLD) is too small, you’ll get lots of tiny tasks — the cost of creating and synchronizing them will exceed the gains from parallelism. Experiment with the threshold: optimal values are often in the thousands or tens of thousands of elements.

Error #2: Using shared mutable variables. If subtasks write to a shared variable without synchronization, you’ll get data races (race condition). Return results via compute() and merge only in join().

Error #3: Incorrect use of fork/join. If you forget to call fork() or join(), the subtask won’t run in parallel or its result will be “lost”. Pay close attention to the call order.

Error #4: Running a ForkJoinTask outside of a ForkJoinPool. If you just call compute() on a task, it will run in the current thread with no parallelism. For the real magic, use pool.invoke() or pool.submit().

Error #5: Ignoring exceptions. If an exception occurs inside a task, it will surface when you call join() or invoke(). Don’t forget to handle errors.

Error #6: Using ForkJoinPool for blocking tasks. ForkJoinPool is a poor fit for tasks that block frequently (wait for I/O, etc.). In such cases it’s better to use ExecutorService.

1
Task
JAVA 25 SELF, level 54, lesson 3
Locked
Task Distribution for Digital Accountants 💼
Task Distribution for Digital Accountants 💼
1
Task
JAVA 25 SELF, level 54, lesson 3
Locked
Decrypting the Cryptographic Code 🕵️‍♀️
Decrypting the Cryptographic Code 🕵️‍♀️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION