-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathProblem$15.java
68 lines (61 loc) · 1.82 KB
/
Problem$15.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package chapter_thirty_two;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
/**
* *32.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.
*
*
* @author Sharaf Qeshta
* */
public class Problem$15
{
public static void main(String[] args)
{
double[] list = new double[9_000_000];
for (int i = 0; i < 9_000_000; i++)
list[i] = Math.random() * 10;
System.out.println(parallelSum(list));
}
public static double parallelSum(double[] list)
{
RecursiveTask<Double> task = new SumTask(list,0, list.length);
ForkJoinPool pool = new ForkJoinPool();
return pool.invoke(task);
}
private static class SumTask extends RecursiveTask<Double>
{
private final static int THRESHOLD = 1000;
double[] list;
int start;
int end;
public SumTask(double[] list, int start, int end)
{
this.list = list;
this.start = start;
this.end = end;
}
@Override
protected Double compute()
{
if (end - start < THRESHOLD)
{
double sum = 0;
for (int i = start; i < end; i++)
sum += list[i];
return sum;
}
else
{
int mid = (start + end) / 2;
RecursiveTask<Double> left = new SumTask(list, start, mid);
RecursiveTask<Double> right = new SumTask(list, mid, end);
left.fork();
right.fork();
return left.join() + right.join();
}
}
}
}