Member-only story

Effective Java! Use Caution When Making Streams Parallel

Kyle Carter
3 min readJun 13, 2021

While nowdays there are many great languages with useful mechanisms to enable safe concurrency like channels in Rust and Go, Java has historically had solid support for enabling concurrency in your code. As time has gone on the mechanisms built in the language to allow safe concurrency have grown. This is no different in Java 8 with streams. By simply adding a processing node of parallel() as part of the stream we can have Java take over the heavy lifting and we can write our stream like normal (at least it feels that way) and Java will handle the necessary splitting of inputs and combining at the end. Alas, we don't have a free lunch here though. We can't simply throw parallel into our streams and expect everything to be better.

The issues with streams and concurrent programming aren’t really different than concurrent programming using other tools in Java. There are cases where it can be of great use and there can be places where it will cause new problems with zero benefit. That being said there are some heuristics that can be used to identify in which cases a parallel stream can be useful. For example, streams that are creating infinite streams with limit processing nodes. This can lead to un-halting code as the code tries to figure out how to properly handle it. Another thing to keep in mind is what the terminal operation of the stream is. If it's a collector, that doesn't lend itself to parallelization as much as, for example, a reduction operation. Another challenge of parallel streams is that by default they…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet