BackendBench
Coffee
Spot the Bug #81

A parallel stream that fills a plain list

A medium Java puzzle in the streams and lambdas family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumStreams and lambdasbuggy line: 7

Highlighted: line 7. Play this one as a puzzle without the answer.

What is wrong

ArrayList is not thread-safe, and a parallel stream calls the lambda from several threads. Elements are lost, the list contains nulls, or an ArrayIndexOutOfBoundsException occurs, so the size is rarely 10,000.

The fix

List<Integer> out = IntStream.range(0, 10_000).parallel().boxed().map(i -> i * i).collect(Collectors.toList());

How to avoid it next time

Let collectors build results. Never mutate shared non-thread-safe state from a parallel stream.

Want the background? Read Parallel streams in the Java concepts library.

About streams and lambdas

Streams are single-use and lazy, and lambdas can only capture effectively final variables. Side effects inside stream pipelines and parallel streams over shared state are frequent sources of surprise.

In code review: Check whether a stream variable is used twice, whether the terminal operation is present, and whether any lambda mutates outside state.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #80#82 โ†’

Frequently asked questions

What is the bug in "A parallel stream that fills a plain list"?

ArrayList is not thread-safe, and a parallel stream calls the lambda from several threads. Elements are lost, the list contains nulls, or an ArrayIndexOutOfBoundsException occurs, so the size is rarely 10,000. The faulty line is line 7: IntStream.range(0, 10_000).parallel().forEach(i -> out.add(i * i));

How do I fix it?

Replace it with: List out = IntStream.range(0, 10_000).parallel().boxed().map(i -> i * i).collect(Collectors.toList());. Let collectors build results. Never mutate shared non-thread-safe state from a parallel stream.

How do I catch streams and lambdas in code review?

Check whether a stream variable is used twice, whether the terminal operation is present, and whether any lambda mutates outside state.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need