When it comes to stream in Java 8, there are 2 different types of stream operation available. They are serial stream and parallel stream. In this article we will be discussing about parallel stream in java 8. We will look into different examples of using parallel stream, differences between them, performance improvement with parallel stream and also discuss about some aspects of using parallel stream.
Parallel stream enables parallel computing that involves processing elements concurrently in parallel with each element in a seperate thread. But this does not guarantee high performance and faster execution everytime. It again depends on the number of CPU cores available.
Parallelstream has a much higher overhead compared to a sequential one.Parallel stream should be used only when there is a huge amount of elements to process and there is a performance problem with processing these elements. Also the parallel stream operations should be independent.
We can create a parallel stream from existing stream by using parallel(). Following is an example:
Another way to create parallelstream is using parallelStream() method.
Following is an example using parallel stream that counts number of prime numbers between 1 and 50.Stream of numbers is created by a range method and then the stream is converted to parallel stream.
Output : Count - 15
If we use serial stream the order is guaranted as below:
Whereas, the order is not guaranted while using parallel stream.
Parallel stream providdes significant performance improvement for larger streams. Following is an example that processes large streams and compares the time difference between processing time of sequential stream and parallel stream.ParallelStreamPerformanceCheck.java
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.
©2017, DevGlan. All Rights Reserved.
Contact us: email@example.com