// A simple example that uses RecursiveTask<V>.
import [Link].*;
// A RecursiveTask that computes the summation of
an array of doubles.
class Sum extends RecursiveTask<Double> {
// The sequential threshold value.
final int seqThresHold = 500;
// Array to be accessed.
double[] data;
// Determines what part of data to process.
int start, end;
Sum(double[] vals, int s, int e ) {
data = vals;
start = s;
end = e;
}
// Find the summation of an array of doubles.
protected Double compute() {
double sum = 0;
if((end - start) < seqThresHold) {
for(int i = start; i < end; i++) sum
+= data[i];
}
else {
int middle = (start + end) / 2;
Sum subTaskA = new Sum(data, start,
middle);
Sum subTaskB = new Sum(data, middle,
end);
[Link]();
[Link]();
// Wait for the subtasks to return, and aggregate
the results.
sum = [Link]() +
[Link]();
}
// Return the final sum.
return sum;
}
}
// Demonstrate parallel execution.
class RDemo {
public static void main(String[] args) {
// Create a task pool.
ForkJoinPool fjp = new ForkJoinPool();
double[] nums = new double[10];
// Initialize nums with values that alternate
between
// positive and negative.
for(int i=0; i < [Link]; i++)
nums[i] = (double) i ;
Sum task = new Sum(nums, 0, [Link]);
// Start the ForkJoinTasks. Notice that, in this
case,
// invoke() returns a result.
double summation = [Link](task);
[Link]("Summation " +
summation);
}
}