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.
Fork/Join uses a special thread pool called ForkJoinPool. Tasks extend either RecursiveTask or RecursiveAction and override the compute() method.
// Example of RecursiveAction without return value
class MyTask extends RecursiveAction {
protected void compute() {
// Task logic goes here
System.out.println("Task executed");
}
}
// 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;
}
}
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.
Simulating sum of array: [10, 20, 30, 40]
RecursiveAction