Junior — Middle
How does ForkJoinPool differ from FixedThreadPool in thread management?
sobes.tech AI
Answer from AI
FixedThreadPool and ForkJoinPool are different types of thread pools in Java, designed for different tasks.
-
FixedThreadPool creates a pool with a fixed number of threads. It is suitable for executing independent tasks that can run in parallel but do not require interaction with each other. Tasks are queued and executed as threads become available.
-
ForkJoinPool is optimized for tasks that can be broken down into subtasks (divide and conquer). It uses a work-stealing algorithm, where threads that become free can take tasks from other threads' queues, increasing efficiency in recursive or parallel computations.
Example of using ForkJoinPool for parallel array sum:
import java.util.concurrent.*;
class SumTask extends RecursiveTask<Integer> {
private int[] arr;
private int start, end;
private static final int THRESHOLD = 10;
SumTask(int[] arr, int start, int end) {
this.arr = arr;
this.start = start;
this.end = end;
}
protected Integer compute() {
if (end - start <= THRESHOLD) {
int sum = 0;
for (int i = start; i < end; i++) sum += arr[i];
return sum;
} else {
int mid = (start + end) / 2;
SumTask left = new SumTask(arr, start, mid);
SumTask right = new SumTask(arr, 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);
In summary:
- FixedThreadPool — for a fixed number of threads and regular tasks.
- ForkJoinPool — for recursive, divide-and-conquer tasks with efficient load balancing.