Java Fork Join Framework calculate array of double

Introduction

The following program creates a fork/join task that transforms an array of doubles.



import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

class Transform extends RecursiveAction {
  int seqThreshold;
  double[] data;/*  w  ww  .  ja  v  a  2  s .com*/
  int start, end;

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

  protected void compute() {
    if ((end - start) < seqThreshold) {
      for (int i = start; i < end; i++) {
         data[i] = Math.cos(data[i]);
      }
    } else {
      int middle = (start + end) / 2;
      invokeAll(new Transform(data, start, middle, seqThreshold), new Transform(data, middle, end, seqThreshold));
    }
  }
}

// Demonstrate parallel execution.
public class Main {

  public static void main(String args[]) {
    int pLevel = 2;
    int threshold = 3;

    // These variables are used to time the task.
    long beginT, endT;

    ForkJoinPool fjp = new ForkJoinPool(pLevel);

    double[] nums = new double[1000000];

    for (int i = 0; i < nums.length; i++) {
      nums[i] = (double) i;
    }
    Transform task = new Transform(nums, 0, nums.length, threshold);

    beginT = System.nanoTime();

    fjp.invoke(task);

    endT = System.nanoTime();

    System.out.println("Level of parallelism: " + pLevel);
    System.out.println("Sequential threshold: " + threshold);
    System.out.println("Elapsed time: " + (endT - beginT) + " ns");
    System.out.println();
  }
}



PreviousNext

Related