Command Palette

Search for a command to run...

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

How sources split: ArrayList versus LinkedList

LinkedList splits by copying a batch (starting at 1024 elements) into an array, so a small list goes to one thread entirely: no parallelism at all.

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?

How sources split: ArrayList versus LinkedList Java 16+
Sign in to run this example in your browser.

Expected output

ArrayList, first split: 8 + 8
second split: 4 + 4 + 8
first quarter holds: 1 2 3 4
ArrayList knows exact sizes: true
LinkedList split: 16 + 0
iterate + limit knows its size: false