Stream() and parallelStreams()

Asked

Viewed 2,555 times

7

I saw that the performance using Amble and streams is much better than using repeat loops, so I try to use as much as possible.
My question is when should I wear Streams or Parallelstreams? How does this stream parallelism occur?

1 answer

8


The Streams API available from Java 8, has come to bring 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: Multi-core Cpus - Why My Application Doesn’t Use All Processor Cores?

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 a Stream is run in parallel, java partitions or splits Streams in various substreams. Aggregation operations iterate and process these substreams in parallel and then combine the results.

Source: https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html

In other words

The intention of Parallel stream, is to allow the processing to be divided between the processors of your machine, for example, if you need to order a large Collection, this can be done in a serial way, and consequently by a single Thread, or in parallel with two or more Threads.

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

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

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

  • Depends on which operations in Streams you use, not all are in fact parallelized

Sources:

https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html

http://java.dzone.com/articles/whats-wrong-java-8-part-iii

  • I liked the explanation of the Parallel stream.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.