Senior
Tell about ThreadPool, ForkJoinPool, and its features.
sobes.tech AI
Answer from AI
ThreadPool is a pool of threads that manages a set of worker threads for executing tasks. It allows reusing threads, reducing the overhead of creating and destroying them.
ForkJoinPool is a specialized thread pool optimized for tasks that can be recursively broken down into subtasks (fork) and then combined (join). It implements the "divide and conquer" algorithm.
Features of ForkJoinPool:
- Uses work-stealing algorithm: threads that have no work can steal tasks from other threads, increasing efficiency.
- Supports parallel execution of a large number of small tasks.
- Often used with RecursiveTask or RecursiveAction classes for recursive task division.
Example of using ForkJoinPool:
class SumTask extends RecursiveTask<Integer> {
private int[] array;
private 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;
}
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;
}
}
}
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));
Thus, ThreadPool is suitable for general thread management, while ForkJoinPool is for parallel recursive tasks with dynamic load balancing.