Java RecursiveTask class

Introduction

The following code extends RecursiveTask class to create a task called Sum.

It sums the values in an array of double.

// A simple example that uses RecursiveTask<V>. 
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

class Sum extends RecursiveTask<Double> {
  final int seqThresHold = 500;
  double[] data;// ww  w .j  a  v a2  s  . c o m
  int start, end;

  Sum(double[] vals, int s, int e) {
    data = vals;
    start = s;
    end = e;
  }

  protected Double compute() {
    double sum = 0;
    if ((end - start) < seqThresHold) {
      for (int i = start; i < end; i++)
        sum += data[i];
    } else {
      // Otherwise, continue to break the data into smaller peices.

      // Find the midpoint.
      int middle = (start + end) / 2;

      // Invoke new tasks, using the subdivided data.
      Sum subTaskA = new Sum(data, start, middle);
      Sum subTaskB = new Sum(data, middle, end);

      // Start each subtask by forking.
      subTaskA.fork();
      subTaskB.fork();

      // Wait for the subtasks to return, and aggregate the results.
      sum = subTaskA.join() + subTaskB.join();
    }
    return sum;
  }
}

// Demonstrate parallel execution.
public class Main {
  public static void main(String args[]) {
    // Create a task pool.
    ForkJoinPool fjp = new ForkJoinPool();

    double[] nums = new double[5000];

    for (int i = 0; i < nums.length; i++)
      nums[i] = (double) (((i % 2) == 0) ? i : -i);

    Sum task = new Sum(nums, 0, nums.length);

    double summation = fjp.invoke(task);

    System.out.println("Summation " + summation);
  }
}



PreviousNext

Related