Command Palette

Search for a command to run...

Back to the lesson: Topic 10.8 — Parallel Streams and Their Pitfalls
Core Java · Example 2 of 4 Java 16+

Accumulate results the safe way

Compare with forEach(evens::add) into a plain ArrayList, which loses elements or throws, differently on every run (see the walkthrough).

Calling parallelStream() or .parallel() splits a stream's work across the threads of the shared fork/join pool. It gives the same answer as a sequential stream only if your operations are stateless, non-interfering and associative, and it's faster only for large, CPU-heavy work on sources that split well.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Compute the number of primes below 200,000 with a parallel IntStream and a simple isPrime method, and check it equals the sequential count.

02

Fix this racy code without using any locks: int[] total = {0}; IntStream.rangeClosed(1, 1000).parallel().forEach(n -> total[0] += n);. Print the correct total.

03

Count words by length in parallel with groupingByConcurrent and print the result as a sorted map, for "a bb cc ddd e ff ggg hhhh".

Explain it without notes

01

How does a parallel stream split and execute work?

02

What conditions must a pipeline meet to give correct results in parallel?

03

When does a parallel stream actually make things faster, and when slower?

04

Why is blocking I/O inside a parallel stream a problem?

05

How do ordering guarantees differ between forEach, forEachOrdered, findFirst, findAny and toList in parallel?

Accumulate results the safe way Java 16+
Sign in to run this example in your browser.

Expected output

collect size: 50000, first 0, last 99998
count: 33334
LongAdder: 100000
groupingByConcurrent: {0=10000, 1=10000, 2=10000, 3=10000, 4=10000, 5=10000, 6=10000, 7=10000, 8=10000, 9=10000}