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.
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