You should probably read this before using parallel Streams !
Have you ever wondered “what’s the benefit of using a parallel Stream instead of a sequential Stream in Java” ?
A long time ago, I asked myself this question and at that time I found a nice article with benchmarks. Recently, I tried to get my hands on it again but impossible to find the article. So I did some benchmarks on my own and I will share the results with you.
Context
First some background: the Stream API is available in the JDK since the version 8 released in 2014. So I assume that now most of you will know what is a Stream and how to use it, but I will explain the specifics between a sequential Stream and a parallel one.
To understand the specifics of parallel Streams we need to first understand some basics of Stream in general. Streams are composed of three components: a source, some intermediate operations and a terminal operation.
- The source is the operation generating the data from which a stream will be applied. You can create Streams from any
Collection
,Array
or you can even create one withStream.of()
. There are more ways to create Streams, those were just examples. To create a parallel Stream you have several possibilities: you can directly create the Stream as parallel from aCollection
withmyCollection.parallelStream()
or you can use the intermediate operation.parallel()
on an existing Stream to transform it into a parallel Stream; - Intermediate…