Java.Multithreading.What is a “Fork/Join framework”?

The Fork/Join Framework is a powerful tool in Java for parallel programming, especially when you want to break a big task into smaller ones, work on them in parallel, and combine the results.


⚙️ What is the Fork/Join Framework?

It’s a framework for parallelism in Java introduced in Java 7 under java.util.concurrent.

It uses a work-stealing algorithm to efficiently use all CPU cores by splitting tasks (forking) and combining results (joining).


🧠 Core Concepts

TermMeaning
fork()Divide the task into smaller subtasks and run them asynchronously
join()Wait for the completion of subtasks and combine results
RecursiveTask<V>For tasks that return a result
RecursiveActionFor tasks that don’t return a result
ForkJoinPoolSpecial thread pool that manages and executes fork/join tasks

✅ Real-World Analogy

Imagine you’re trying to count the number of files in a big folder. Instead of checking each file/folder one by one, you:

  1. Split the job into subfolders ✅ (fork)
  2. Count files in each subfolder in parallel ✅
  3. Combine the counts ✅ (join)

🔧 Example: Sum Array in Parallel

class SumTask extends RecursiveTask<Integer> {
    private final int[] arr;
    private final int start, end;

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

    @Override
    protected Integer compute() {
        if (end - start <= 10) { // small enough
            int sum = 0;
            for (int i = start; i < end; i++) sum += arr[i];
            return sum;
        }

        int mid = (start + end) / 2;
        SumTask left = new SumTask(arr, start, mid);
        SumTask right = new SumTask(arr, mid, end);

        left.fork(); // run left asynchronously
        int rightResult = right.compute(); // run right in current thread
        int leftResult = left.join(); // wait for left to finish

        return leftResult + rightResult;
    }
}

🧪 Using It:

ForkJoinPool pool = new ForkJoinPool();
int[] data = IntStream.range(1, 1001).toArray();
int result = pool.invoke(new SumTask(data, 0, data.length));
System.out.println("Sum: " + result);

🧠 Why Use It?

BenefitDescription
🧵 Uses all CPU coresTasks are run in parallel
⚡ Fast for divide-and-conquerGreat for recursive tasks (sorting, searching, etc.)
🤖 Work-stealingIdle threads “steal” work from busy threads

📌 When to Use Fork/Join

Use it when:

  • Your problem can be broken down into subproblems
  • You want to leverage multi-core CPUs
  • You’re implementing parallel algorithms like merge sort, file scanning, or matrix multiplication
This entry was posted in Без рубрики. Bookmark the permalink.