Streams are lazy until a terminal operation runs. Why does that matter, and when would you make one parallel?
Laziness means intermediate operations only describe a pipeline, so nothing traverses the source until a terminal operation pulls, and short-circuiting operations can stop early. Parallel helps when the source splits evenly, the work per element is CPU-bound and substantial. Use this streams answer to show the decision, trade-off, and evidence rather than a memorised definition.
Answer
Short answer
Java parallel streams help when the source splits cheaply, the work per element is CPU-heavy, and the collector or terminal operation can combine results safely. They usually hurt for blocking I/O, tiny tasks, ordered pipelines, shared mutable state or sources that split poorly, because the common pool and coordination overhead dominate.
Was this answer helpful?
Likely follow-ups
- Why can a side effect inside peek fail to run at all?
- Collectors.toMap throws on a duplicate key. What else does it reject that groupingBy accepts?
- What is the difference between forEach and forEachOrdered on a parallel stream?
- Why is a stream one-shot, and what do you return from a method instead when the caller may need to traverse twice?
Related questions
- Walk me through writing your own Collector. What do its four functions do, and what do the characteristics promise the pipeline?hardAlso on streams and collectors5 min
- Why would you stream a large file rather than read it into memory, and what is backpressure?mediumAlso on streams4 min
- How do generators reduce memory use, and when are they the wrong choice?mediumAlso on laziness5 min
- Your Collectors.toMap call passed every test and threw in production. What did the code assume, and what are your options?mediumAlso on streams4 min