Junior — Middle
Can you explain the concept of Fork/Join and how it is used for parallel task processing?
sobes.tech AI
Answer from AI
Fork/Join is a parallel task processing model that breaks a large task into smaller subtasks (fork), executes them in parallel, and then combines (join) the results of these subtasks.
In Java, this concept is implemented through the ForkJoinPool class and the abstract classes RecursiveTask or RecursiveAction. The main idea:
- The task checks if it is small enough for direct computation.
- If not, the task is divided into several subtasks (fork).
- The subtasks are executed in parallel in the ForkJoinPool thread pool.
- After the subtasks complete, their results are combined (join) to obtain the final result.
Example: calculating the sum of array elements using Fork/Join
import java.util.concurrent.*;
class SumTask extends RecursiveTask<Integer> {
private final int[] array;
private final int start, end;
private static final int THRESHOLD = 10;
SumTask(int[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
if (end - start <= THRESHOLD) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
return sum;
} else {
int mid = (start + end) / 2;
SumTask leftTask = new SumTask(array, start, mid);
SumTask rightTask = new SumTask(array, mid, end);
leftTask.fork(); // start the left subtask asynchronously
int rightResult = rightTask.compute(); // compute the right subtask in the current thread
int leftResult = leftTask.join(); // wait for the left subtask result
return leftResult + rightResult;
}
}
}
// Usage:
// ForkJoinPool pool = new ForkJoinPool();
// int result = pool.invoke(new SumTask(array, 0, array.length));
This approach allows efficient utilization of multi-processor systems to accelerate computations.