java8-parallelstream

偶尔善良 提交于 2021-02-19 05:02:32

Parallel stream

Fork and join

Pseudocode

If(task is small enough or no longer divisible){

Compute task sequentially

}else{

split task in two subtasks

call this method recursively possibly further splitting  each subtask

wait for the completion of all subtasks

combine the results of each subtask}

 

 

 

 

public class ForkJoinSumCalculator extends RecursiveTask<Long> {

   
private final long[] numbers;
   
private final int start;
   
private final int end;
   
public static final long THRESHOLD = 10_1000;


   
public ForkJoinSumCalculator(long[] numbers) {
       
this(numbers, 0, numbers.length);

    }

   
public ForkJoinSumCalculator(long[] numbers, int start, int end) {
       
this.numbers = numbers;
       
this.start = start;
       
this.end = end;

    }


   
@Override
   
protected Long compute() {

       
int length = end - start;
       
if (length <= THRESHOLD) {
           
return computeSequentially();
        }
        ForkJoinSumCalculator leftTask =
new ForkJoinSumCalculator(numbers, start, start + length / 2);
        leftTask.fork();
        ForkJoinSumCalculator rightTask =
new ForkJoinSumCalculator(numbers, start + length / 2, end);
        Long rightResult = rightTask.compute();
        Long leftResult = leftTask.join();
       
return leftResult + rightResult;
    }

   
private long computeSequentially() {
       
long sum = 0;
       
for (int i = start; i < end; i++) {
            sum +=
numbers[i];
        }
       
return sum;
    }

   
public static long forkJoinSum(long n){
       
long[] numbers= LongStream.rangeClosed(1,n).toArray();
        ForkJoinTask<Long> task=
new ForkJoinSumCalculator(numbers);
       
return new ForkJoinPool().invoke(task);
    }
}

@Test

public void test(){

    long i = 10000000;

    StopWatch stopWatch=new StopWatch();

    stopWatch.start();

    Function<Long,Long> adder=ForkJoinSumCalculator::forkJoinSum ;

    adder.apply(i);

    stopWatch.stop();

    System.out.println(stopWatch.getTotalTimeSeconds());







}

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!