← Back to Chapters

Fork/Join Framework

⚙️ Fork/Join Framework

? Quick Overview

The Fork/Join Framework is a powerful concurrency framework introduced in Java 7. It is designed to efficiently execute large tasks by splitting them into smaller subtasks, processing them in parallel, and then joining the results.

? Key Concepts

  • Fork: Split a task into smaller subtasks
  • Join: Combine results of subtasks
  • RecursiveTask<V>: Returns a result
  • RecursiveAction: Does not return a result
  • Work-Stealing: Idle threads steal tasks from busy threads

? Syntax & Theory

Fork/Join uses a special thread pool called ForkJoinPool. Tasks extend either RecursiveTask or RecursiveAction and override the compute() method.

? View Code Example
// Example of RecursiveAction without return value
class MyTask extends RecursiveAction {

    protected void compute() {
        // Task logic goes here
        System.out.println("Task executed");
    }
}

? Code Example — Fork/Join Sum

? View Code Example
// RecursiveTask to calculate sum of an array using Fork/Join
class SumTask extends RecursiveTask<Long> {

    private int[] arr;
    private int start;
    private int end;

    SumTask(int[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    protected Long compute() {
        // Threshold to decide when to split the task
        if (end - start <= 5) {
            long sum = 0;
            for (int i = start; i < end; i++) {
                sum += arr[i];
            }
            return sum;
        }

        int mid = (start + end) / 2;

        // Fork subtasks
        SumTask left = new SumTask(arr, start, mid);
        SumTask right = new SumTask(arr, mid, end);

        left.fork();
        long rightResult = right.compute();
        long leftResult = left.join();

        return leftResult + rightResult;
    }
}

? Live Output / Explanation

The array is recursively divided into smaller parts. Each subtask computes a partial sum in parallel. Finally, all partial sums are joined to produce the total sum efficiently.

? Interactive Visualization

Simulating sum of array: [10, 20, 30, 40]

Ready to start...
Task
Left
Right
10
20
30
40

? Tips & Best Practices

  • Use Fork/Join for CPU-intensive tasks
  • Keep tasks small but not too small
  • Avoid blocking operations inside compute()
  • Prefer immutable shared data

? Try It Yourself

  • Modify the threshold value and observe performance
  • Convert the example to use RecursiveAction
  • Use Fork/Join to perform parallel file processing