Video in progress

Strong Middle 🌊 Streams and lambdas

Why can sorted() or distinct() make a program hang on an infinite stream?

sorted() can't emit even the first element until it has received all of them, and on an infinite stream there is no "all": it collects until memory runs out. distinct() does emit elements, but if no new unique value ever arrives, limit never fills and the stream doesn't stop.

📖 Answer

Two examples:

// 1) never ends, finally an OutOfMemoryError
Stream.generate(() -> random.nextInt(100))
        .sorted()
        .limit(5)
        .toList();

// 2) hangs: only values 0..9 exist, there aren't 11 unique ones
Stream.generate(() -> random.nextInt(10))
        .distinct()
        .limit(11)
        .toList();

The first is easy to fix: put limit before sorted. The second is a logic error, and you fix it only by understanding it.

The concept of short-circuiting matters here. limit, findFirst, anyMatch and takeWhile are short-circuit operations, which can finish an infinite stream in finite time. But a "barrier" in front of them (sorted, and in some cases a parallel limit) needs the whole source and cancels the short-circuit.

In prod this usually shows up not with an infinite stream but with a very large source: sorted() on a Files.lines(...) with millions of lines, or on data streamed from a database, and everything lands in the heap. If you see a large ArrayList containing SortedOps in a heap dump, this is the case.

If the source is naturally sorted, hand the sorting to the database (ORDER BY) and work with takeWhile in the stream.