Tuesday, May 12, 2015

Sum of 1 to 10000 using ForkJoinPool framework

 import java.util.ArrayList;  
 import java.util.Arrays;  
 import java.util.List;  
 import java.util.concurrent.RecursiveTask;  
 public class ArraySplit extends RecursiveTask<Long>{  
      /**  
       *   
       */  
      private static final long serialVersionUID = 1L;  
      private Integer[] list;  
      public ArraySplit() {}  
      List<ArraySplit> taskList = new ArrayList<ArraySplit>();  
      public ArraySplit(Integer[] list) {  
           this.list = list;  
      }  
      @Override  
      protected Long compute() {  
           int sum = 0;  
           if(list.length <= 1000){  
                for(int i:list){  
                     sum += i;  
                }  
           }else{  
                int midpoint = list.length / 2;  
                Integer[] l1 = Arrays.copyOfRange(list, 0, midpoint);   
                Integer[] l2 = Arrays.copyOfRange(list, midpoint, list.length);  
                ArraySplit st1 = new ArraySplit(l1);      st1.fork();  
                ArraySplit st2 = new ArraySplit(l2);     st2.fork();  
                taskList.add(st1);  
                taskList.add(st2);  
           }  
           return addResultFromSubTask(sum, taskList);  
      }  
      private Long addResultFromSubTask(int sum, List<ArraySplit> taskList){  
           int result = 0;  
           for(ArraySplit splitTask: taskList){  
                result += splitTask.join();  
           }  
           return (long) (result + sum);  
      }  
 }  


Above code divides the long array into multiple sub-array. Sum of sub-array value is combined with other sub-array sum value and is returned to the calling method. Sum of sub-arrays is handled by different thread results in faster calculation.

No comments:

Post a Comment