Junior — Middle
Explain what the RecursiveTask class is in Java's parallel computing?
sobes.tech AI
Answer from AI
The RecursiveTask class in Java is an abstract class from the java.util.concurrent package, designed for implementing parallel computations using the Fork/Join framework. It is used when a task can be recursively divided into subtasks, and the result of each subtask needs to be combined to obtain the final result.
Main points:
- By inheriting from
RecursiveTask<V>, you implement thecompute()method, where you define the logic for dividing the task. - If the task is small enough, it is executed directly.
- If the task is large, it is split into several subtasks, which are run in parallel using
fork(), and then the results are combined usingjoin().
Example: calculating the sum of array elements using RecursiveTask:
import java.util.concurrent.RecursiveTask;
public class SumTask extends RecursiveTask<Integer> {
private static final int THRESHOLD = 10;
private int[] array;
private int start, end;
public SumTask(int[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int length = end - start;
if (length <= THRESHOLD) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
return sum;
} else {
int mid = start + length / 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;
}
}
}
Thus, RecursiveTask helps efficiently parallelize tasks that naturally break down into subtasks with results.