Junior — Middle
What is the main function and application of ForkJoinPool in Java for parallel computing?
sobes.tech AI
Answer from AI
ForkJoinPool is a specialized thread pool in Java designed for efficient execution of tasks that can be recursively broken down into smaller subtasks (the "divide and conquer" approach). It implements the Fork/Join algorithm, allowing parallelization of computations and effective utilization of multi-core processors.
The main idea: a task is divided into subtasks, which are executed in parallel, and then the results are combined. This is especially useful for tasks with a high degree of parallelism, such as merge sort, processing large data arrays.
Example of usage:
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 left = new SumTask(array, start, mid);
SumTask right = new SumTask(array, mid, end);
left.fork();
int rightResult = right.compute();
int leftResult = left.join();
return leftResult + rightResult;
}
}
}
// Usage
ForkJoinPool pool = new ForkJoinPool();
int[] data = {1,2,3,4,5,6,7,8,9,10};
int result = pool.invoke(new SumTask(data, 0, data.length));
System.out.println("Sum: " + result);
Thus, ForkJoinPool simplifies the creation and management of parallel tasks with dynamic splitting.