
package forkjoinExample;

import java.util.concurrent.*;

public class ForkJoinExample {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                       11,12,13,14,15,16,17,18,19,20
                      };
        
        ForkJoinPool pool = new ForkJoinPool();
       
        long startTime = System.nanoTime();
        
        int sum = pool.invoke(new SumTask(array));
        
        pool.shutdown();
        
        long endTime = System.nanoTime();
        
        System.out.println("Sum = " + sum);
        System.out.println("Time taken: " + (endTime - startTime) + " nanoseconds");
    }
}

class SumTask extends RecursiveTask<Integer> {
    private int[] array;
    private int start;
    private int end;
    
    public SumTask(int[] array) {
        this(array, 0, array.length);
    }
    
    public SumTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }
    
    @Override
    protected Integer compute() {

//--------> VARIABLE N

        int N = 32;
        
//--------> VARIABLE N

        if (end - start <= N) {
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        } 
        else {
            int mid = start + (end - start) / 2;
            
            SumTask left = new SumTask(array, start, mid);
            SumTask right = new SumTask(array, mid, end);
            
            
            left.fork();
            
            int rightSum = right.compute();
            
            int leftSum = left.join();
            
            return leftSum + rightSum;
        }
    }
}
