Video in progress
How does work-stealing in ForkJoinPool work, and when should you not use a parallel stream?
Each worker has its own deque: it takes its own tasks from one end, and a worker that runs out of work "steals" from the other end of another's deque. That is great for divisible CPU work, but for blocking I/O or small data, a parallel stream does harm, not good.
📖 Answer
A ForkJoinTask splits the work (fork) and puts the small pieces into the deque. A worker takes from the head of its own deque in LIFO order, which is cache-friendly because the recently split data is still in the cache. An idle worker takes from the end of another deque in FIFO order, where the biggest, not-yet-split pieces usually sit. As a result, the load balances itself.
A parallel stream runs on this mechanism, and by default in ForkJoinPool.commonPool().
When it doesn't help:
- Small volume. The cost of splitting 1,000 elements and combining the results is more than the work itself. A rough guide (the NQ model): if the number of elements times the number of simple operations per element is under 10,000, or if the sequential version finishes in under 100 microseconds, there is no point in going parallel.
- A source that splits badly.
LinkedList,Stream.iterateand a stream read from I/O don't split well;ArrayList, arrays andIntStream.rangedo. - Blocking work.
parallelStream().map(this::callApi)takes over the common pool and stalls other parallel code in the JVM. - Order-dependent operations.
forEachOrdered,limitandfindFirstcancel out the parallelism. - Shared mutable state.
parallelStream().forEach(list::add)is a race on theArrayList. Usecollect(...).
Using a parallel stream inside a request in a web service is often a bad idea: the server is already running many requests in parallel, and extra parallelism only adds contention. I use it for batch jobs and CPU-heavy calculations, after measuring with JMH.
Sign up to mark studied questions and save your progress.