Sitemap
Nuwan Zen

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!

Parallel Computing With Java Streams

2 min readMay 16, 2021

Let’s try to print a list and see how can we use parallel streams in Java streams api.

Press enter or click to view image in full size
Photo by Robert V. Ruggiero on Unsplash
List<Integer> numbers  = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

Now we can print the list like this using sequential coding.

numbers.stream()
.forEach(System.out::println);

Now try the same with parallel streams

numbers.stream()
.parallel()
.forEach(System.out::println);

You will notice that simply adding parallel() will convert the whole code in to parallel computing world. Note that how much Streams API made us using parallel computing easier.

Now let’s think we setting to run steams both parallel and serial in the same statement

numbers.stream()
.parallel()
.map(integer -> integer)
.sequential()
.forEach(System.out::println);

You can ignore below code as it does nothing and just returns the same variable back

.map(integer -> integer)

When parallel and sequential keywords are executed in same code, how will the code be executed?

Will it run half parallel and rest in sequential? No, streams run as segments. As streams are Lazy, execution happens at the last minute and execution starts in backwards, so the code execution will be set to sequential as its the first to find.

Get Nuwan Zen’s stories in your inbox

Join Medium for free to get updates from this writer.

If you want the output sorted in parallel streams you can use forEachOrdered:

numbers.stream()
.parallel()
.forEachOrdered(System.out::println);

This ordering will happen only if the input stream or the list is ordered.

Reduce

Let’s say we need the total of the list

numbers.stream()
.reduce((integer, integer2) -> add(integer,integer2))

In parallel

numbers.stream()
.parallel()
.reduce ((integer, integer2) -> add(integer,integer2));

The only issue with the reduce comes when we try use an identity value with parallel

numbers.stream()
.reduce (identity,(i1, i2) -> i1+i2);

This identity value will add to the total, in this code total is 55 and if we set the identity to 100 then our total will be 155, that is 100 + 55.

numbers.stream()
.parallel()
.reduce (identity,(i, i2) -> i+i2);

If you run this code out put will be 1055. So basically it gives a incorrect value. So it should take care when you work with parallel processing.

Link to My other blog posts:

--

--

Nuwan Zen
Nuwan Zen

Written by Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!