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
Term | Meaning |
---|---|
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 |
RecursiveAction | For tasks that don’t return a result |
ForkJoinPool | Special 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:
- Split the job into subfolders ✅ (
fork
) - Count files in each subfolder in parallel ✅
- 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?
Benefit | Description |
---|---|
🧵 Uses all CPU cores | Tasks are run in parallel |
⚡ Fast for divide-and-conquer | Great for recursive tasks (sorting, searching, etc.) |
🤖 Work-stealing | Idle 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