## Thursday, 2 March 2017

### Chapter 30 Exercise 15, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

30.15 (Parallel sum) Implement the following method using Fork/Join to find the
sum of a list.
public static double parallelSum(double[] list)
Write a test program that finds the sum in a list of 9,000,000 double values.

import java.util.concurrent.ForkJoinPool;

public class Exercise15 {

public static void main(String[] args) {
double[] list = new double[9000000];
for (int i = 0; i < list.length; i++) {
list[i] = Math.random();
}
System.out.print(parallelSum(list));
}

public static double parallelSum(double[] list) {
ForkJoinPool pool = new ForkJoinPool();
}

private static final long serialVersionUID = 1L;
private final static int THRESHOLD = 1000;
private double[] list;
private int low;
private int high;

public SumTask(double[] list, int low, int high) {
this.list = list;
this.low = low;
this.high = high;
}

@Override
protected Double compute() {
if (high - low < THRESHOLD) {
double sum = 0;
for (int i = low; i < high; i++) {
sum += list[i];
}
return sum;
} else {
int mid = (low + high) / 2;

right.fork();
left.fork();
return left.join() + right.join();
}
}

}
}