Stream () and parallelStreams ()

6

I've seen lambdas performance and streams much better than using repetition loops, so I try to use as much as possible.
My question is when should I use Streams or ParallelStreams? How does this parallelism of streams occur?

    
asked by anonymous 03.07.2015 / 16:49

1 answer

7

The Streams API available from Java 8 now has several benefits, let's first define the serial algorithm vs. the parallel algorithm.

I recommend reading this question, my answer seeks to explore these two paradigms of computing: #

Now that we understand parallelism, let's go to Streams ...

According to Oracle

You can run Stream in series or in parallel ( Serial or Parallel ). When Stream is executed in parallel, java partitions or splits Stream s into various substreams. Aggregation operations iterate and process these substreams in parallel, and then combine the results.

Source: link

In other words

Parallel stream is intended to allow processing to be split between the processors on your machine, for example, if you need to sort a large Collection , this can be done serially , and consequently by a single Thread , or in parallel, with two or more Threads .

What it means to say that Collection is broken into two subcollections, and ordered in parallel, which in theory reduces the time spent in half.

The point of great importance is: this is not always true. Even why this may depend on how many processors you have.

    Parallel Streams can make your program faster, or not, and even slower.

  • Depends on which operations in Stream s you use, not all are actually parallelized

Sources:

link

link

    
03.07.2015 / 19:43