/* Using Java's Fork Join Framework to implement * the sum over an array */ import java.util.*; import java.util.concurrent.*; import java.util.stream.*; public class ForkJoinRecursiveSum { public static final int SEQUENTIAL_THRESHOLD = 10; static class Problem extends RecursiveTask { private int lo, hi; private long[] arr; Problem(long[] arr, int lo, int hi) { this.lo = lo; this.hi = hi; this.arr = arr; } @Override public Long compute() { if (hi - lo <= SEQUENTIAL_THRESHOLD) { return Arrays.stream(arr, lo, hi).sum(); } else { int mid = (lo + hi) / 2; var leftHalf = new Problem(arr, lo, mid).fork(); var rightHalf = new Problem(arr, mid, hi).fork(); // tasks now run in parallel return leftHalf.join() + rightHalf.join(); } } } public static void main(String[] args) throws InterruptedException { long[] arr = LongStream.rangeClosed(1, 100).toArray(); ForkJoinPool fjPool = new ForkJoinPool(); long sum = fjPool.invoke(new Problem(arr, 0, arr.length)); System.out.println("Sum: " + sum); } }