import java.util.concurrent.*; import java.util.*; public class SumArray extends RecursiveTask { static final ForkJoinPool fjPool = new ForkJoinPool(); int[] array; int lo, hi; static final int SEQUENTIAL_CUTOFF = 1000; public SumArray (int[] arr, int l, int h) { array = arr; lo = l; hi = h; } public Integer compute() { if (hi-lo <= SEQUENTIAL_CUTOFF) { int ans = 0; for(int i = lo; i < hi; i++) ans += array[i]; return ans; } else { SumArray left = new SumArray(array, lo, (hi+lo)/2); SumArray right = new SumArray(array, (hi+lo)/2, hi); left.fork(); int rightAns = right.compute(); int leftAns = left.join(); return rightAns + leftAns; } } public static void main(String[] args) { System.out.println("Creating the list of numbers..."); Random r = new Random(); int num = 100000000; int[] a = new int[num]; for(int i = 0; i < a.length; i++) a[i] = r.nextInt(num); System.out.println("Finding the sum..."); int sum = fjPool.invoke(new SumArray(a, 0, a.length)); System.out.println("The sum is: " + sum); } }