Parallel Streams!!

I am always skeptical of using parallel streams in Java8. For simple reason:

You do not have control to decide the pool responsible for executing tasks. By default, common ForkJoinPool executes it.

So in short when you do:

stream.parallel().filter(x -> isPrime(x));

The common pool executes it. And you cannot let some other pool execute `filter` in a straight-forward manner. It gets really dangerous on large codebases where people stupidly using parallel streams. If any computation gets time taking or worse blocking, it impacts all the parallel streams because they all use the same pool.

Though there is a way to let your custom pool execute tasks, but it is insanely irritating (and breakable).

ForkJoinPool pool = new ForkJoinPool(4);
int[] ans = pool.submit(() -> {
            return IntStream.range(1,1000000).parallel().filter(x -> isPrime(x)).toArray();
        }).get();

public static boolean isPrime(int i){
        System.out.println(Thread.currentThread());
        return true;
    }

The above prints Thread[ForkJoinPool-1-worker-0,5,main] rather than Thread[ForkJoinPool.commonPool-worker-2,5,main]. Which means the subtasks are executed by our pool rather than the common pool. It seems magic because we haven’t requested the parallel stream to use our pool. This implicitly happens because of ForkJoinTask#doInvoke internals

private int doInvoke() {
        int s; Thread t; ForkJoinWorkerThread wt;
        return (s = doExec()) < 0 ? s :
            ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
            (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue, this) :
            //else delegate to common pool
    }

Where it checks if the current thread is part of any pool, if so obtains reference to the pool and uses it. Else delegates to common pool.

I haven’t found documentation which suggests above behavior. Hence the behavior cannot be fully trusted.