Java Concurrency Interview

Fork/join and parallel streams question 110 of 180 mid

Why is Stream.iterate a poor source for a parallel stream?

Stream.iterate(0, i -> i + 1) is inherently sequential: element N cannot be produced without producing N-1. Its spliterator cannot split usefully, so the framework buffers chunks and you get the cost of task management with almost none of the parallelism.

IntStream.range(0, n) is the fix where it applies: the range is known, so splitting is exact and free. The general lesson transfers to any source whose next value depends on its last, including reading a file line by line and iterating a LinkedList. If the source cannot be split, parallelism cannot help, no matter how expensive the per-element work is.

parallel-streams performance

Quiz yourself on Fork/join and parallel streams Suggest a correction