Java Fork Join Framework

Main Fork/Join Classes

The Fork/Join Framework is packaged in java.util.concurrent.

At the core of the Fork/Join Framework are the following four classes:

class Description
ForkJoinTask<V>An abstract class that defines a task
ForkJoinPool Manages the execution of ForkJoinTask
RecursiveAction A subclass of ForkJoinTask<V> for tasks that do not return values
RecursiveTask<V> A subclass of ForkJoinTask<V> for tasks that return values

A ForkJoinPool manages the execution of ForkJoinTasks.

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

class SqrtTransform extends RecursiveAction {

  final int seqThreshold = 1000;
  double[] data;/*from  w w  w  .  j  a  v a2 s.co m*/
  int start, end;

  SqrtTransform(double[] vals, int s, int e) {
    data = vals;
    start = s;
    end = e;
  }
  protected void compute() {
    if ((end - start) < seqThreshold) {
      for (int i = start; i < end; i++) {
        data[i] = Math.sqrt(data[i]);
      }
    } else {
      int middle = (start + end) / 2;
      invokeAll(new SqrtTransform(data, start, middle), new SqrtTransform(data, middle, end));
    }
  }
}
public class Main {
  public static void main(String args[]) {
    ForkJoinPool fjp = new ForkJoinPool();
    double[] nums = new double[100000];
    for (int i = 0; i < nums.length; i++)
      nums[i] = (double) i;

    for (int i = 0; i < 10; i++)
      System.out.println(nums[i] + " ");

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

    // Start the main ForkJoinTask.
    fjp.invoke(task);

    for (int i = 0; i < 10; i++){
      System.out.format("%.4f ", nums[i]);
    }
    System.out.println();
  }
}



PreviousNext

Related