Why is filtering by primality in an inifinite stream of numbers taking forever if processed in parallel?

前端 未结 2 532
南方客
南方客 2021-02-14 03:14

I\'m creating an infinite stream of Integers starting at 200 Million, filter this stream using a naive primality test implementation to generate load and limit the result to 10.

2条回答
  •  青春惊慌失措
    2021-02-14 03:43

    The reason why parallel stream taking so long is due to the fact that all parallel streams uses common fork-join thread pool and since you are submitting a long running task(because your implementation of isPrime method is not efficient), you are blocking all threads in the pool and as a result of which all other tasks using parallel stream are blocked.

    In order to make the parallel version faster you can implement isPrime more efficiently. For e.g.

       Predicate isPrime = new Predicate() {
            @Override
            public boolean test(Integer n) {
                if(n < 2) return false;
                if(n == 2 || n == 3) return true;
                if(n%2 == 0 || n%3 == 0) return false;
                long sqrtN = (long)Math.sqrt(n)+1;
                for(long i = 6L; i <= sqrtN; i += 6) {
                    if(n%(i-1) == 0 || n%(i+1) == 0) return false;
                }
                return true;
            }
        };
    

    And immediately you will notice the improvement in the performance. In general avoid using parallel stream when there exists the possibility of blocking threads in the pool

提交回复
热议问题