0% found this document useful (0 votes)
3 views2 pages

RecursiveTask Example

The document presents a Java implementation of a parallel summation algorithm using the Fork/Join framework. It defines a RecursiveTask class, 'Sum', that computes the sum of an array of doubles by dividing the task into subtasks when the array size exceeds a specified threshold. The main class, 'RDemo', demonstrates the execution of this task using a ForkJoinPool to compute and print the summation of an initialized array.

Uploaded by

ushagr
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

RecursiveTask Example

The document presents a Java implementation of a parallel summation algorithm using the Fork/Join framework. It defines a RecursiveTask class, 'Sum', that computes the sum of an array of doubles by dividing the task into subtasks when the array size exceeds a specified threshold. The main class, 'RDemo', demonstrates the execution of this task using a ForkJoinPool to compute and print the summation of an initialized array.

Uploaded by

ushagr
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

// 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);
}
}

You might also like