-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathForkJoinRecursiveTaskDemo.java
43 lines (38 loc) · 1.3 KB
/
ForkJoinRecursiveTaskDemo.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
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
/**
* Fork/Join Framework
* Framework for executing recursive, divide-and-conquer work with multiple processors
* Sample of recursive sum of a range of numbers
*/
public class ForkJoinRecursiveTaskDemo {
private static class RecursiveSum extends RecursiveTask<Long> {
private final long start;
private final long end;
RecursiveSum(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if (end - start <= 100_000) {
long total = 0;
for (long i = start; i <= end; i++) {
total += i;
}
return total;
} else {
long mid = (start + end) / 2;
RecursiveSum left = new RecursiveSum(start, mid);
RecursiveSum right = new RecursiveSum(mid + 1, end);
left.fork();
return right.compute() + left.join();
}
}
}
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool();
long total = pool.invoke(new RecursiveSum(0, 1_000_000_000));
System.out.println(total);
}
}