Java Concurrency Interview

Fork/join and parallel streams question 105 of 180 mid

When is a parallel stream faster, and when is it slower?

The rough rule of thumb is N times Q: the number of elements times the cost per element. If that product is not in the hundreds of thousands of cycles, the splitting, task submission and merging cost more than the parallelism saves.

Four things must hold: enough data, real CPU work per element, a source that splits evenly, and independent elements. ArrayList, arrays and IntStream.range split perfectly. LinkedList, Stream.iterate and a BufferedReader's lines do not: they must be traversed to be split, so one thread does most of the work.

The rest is usually a mistake: blocking I/O in a parallel stream ties up the common pool, limit and findFirst on an ordered stream force coordination, and a stateful lambda is a race waiting to happen. Measure both, on production-shaped data.

parallel-streams performance

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