Juan
Juan

Reputation: 113

Conditions to be careful of while using parallel streams

What condition is required to use parallel streams in java 8? Can we use it in all cases or could it cause some issues in some cases, or should we ensure something before using it?

Upvotes: 2

Views: 442

Answers (1)

GhostCat
GhostCat

Reputation: 140633

The very first thing to understand: the key difference isn't about sequential or parallel streams.

Streams are just one specific concept in java designed for expressing data processing in neat, concise ways. Meaning: you can do sequential or parallel processing completely independent of streams.

Which leads to: the real question is if the problem you intend to solve allows for parallel processing. Many do, others do not. For example: there might be situations where you absolutely have to process "events" in the order they occurred. Then processing a "stream" of such "events in parallel is an absolute no-go. Because parallel always means: losing control over the order of processing.

Beyond that, there is another aspect: performance!

Keep in mind: parallel processing is a trade-off. You are willing to invest more CPU resources (also: code complexity) in order to compute some result earlier. Now: sometimes that trade-off is just not worth it. When you measure sequential vs parallel stream processing, you will find that (depending on many aspects): setting up the parallel stream itself is a pretty expensive operation. Meaning: if your task is to sort 5 objects, then doing that sequentially will always be faster compared to doing it in parallel. Because the sequential sort will long be done before the parallel code actually gets to doing the sorting!

Upvotes: 1

Related Questions