The five smallest numbers of an endless stream
A hard 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.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
sorted is a stateful operation that must see every element before it can emit the first one, and the source never ends. The program hangs and then fails with OutOfMemoryError. limit after sorted does not help; it has to come first.
The fix
How to avoid it next time
Bound infinite streams with limit before any stateful operation such as sorted or distinct.
Want the background? Read Stream operations in depth 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
Frequently asked questions
What is the bug in "The five smallest numbers of an endless stream"?
sorted is a stateful operation that must see every element before it can emit the first one, and the source never ends. The program hangs and then fails with OutOfMemoryError. limit after sorted does not help; it has to come first. The faulty line is line 7: List
How do I fix it?
Replace it with: Stream.generate(() -> r.nextInt(1000)).limit(1000).sorted().limit(5). Bound infinite streams with limit before any stateful operation such as sorted or distinct.
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.