Video in progress

Strong Middle 🌊 Streams and lambdas

Why is calling Stream.concat() many times in a loop dangerous?

Each concat adds a new layer that wraps the previous two streams. If you chain thousands of them, pulling elements goes through deeply nested calls and fails with a StackOverflowError. To combine many sources, use Stream.of(...).flatMap(...).

📖 Answer

The Javadoc itself has a warning: repeated concat can lead to a deep call chain and even a StackOverflowError.

Stream<Event> all = Stream.empty();
for (Partition p : partitions) {              // 10 000 partitions
    all = Stream.concat(all, p.events().stream());
}
all.count();   // StackOverflowError

Each concat adds another level to the tree: the result is unbalanced, a 10,000-level "staircase". To reach the first element, the terminal operation has to go through all of those levels.

The right way:

Stream<Event> all = partitions.stream()
        .flatMap(p -> p.events().stream());

There's no depth here: flatMap opens the inner streams one after another and closes each when it's done.

concat has its place: joining two or three streams once:

Stream<String> headerAndRows = Stream.concat(Stream.of(header), rows.stream());

Two more details. The result of concat is parallel if either of the two streams is parallel. When the result is closed, the close handlers of both sources are called, which is useful when working with Files.lines.

If you see reduce(Stream::concat) in code, it's the same problem: replace it with flatMap(Function.identity()).