Fork/join and parallel streams question 110 of 180 mid
Why is Stream.iterate a poor source for a parallel stream?
- It is infinite
- Correct: Each element depends on the last, so the source cannot be split
- It is not thread safe
- It boxes every element
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.
Quiz yourself on Fork/join and parallel streams Suggest a correction