Video in progress

Strong Middle 🌊 Streams and lambdas

Does a stream inside flatMap short-circuit? What does findFirst() do with an infinite inner stream?

Since Java 10, yes: findFirst, limit and anyMatch stop the inner stream where needed too. In Java 8–9, flatMap read each inner stream to the end: with an infinite inner stream the program would hang, and with an expensive inner stream extra work would be done.

📖 Answer

Optional<Integer> first = Stream.of(1, 2)
        .flatMap(x -> Stream.iterate(x, i -> i + 1))   // each one infinite
        .findFirst();

On Java 17 it returns Optional[1] immediately. On Java 8 this code never finishes: the flatMap implementation pushed the inner stream through with forEach in full and ignored the "enough" signal from downstream. This was recorded as a bug in the JDK and fixed in Java 10.

Why it still matters:

  • In old services running on Java 8, flatMap + findFirst / anyMatch can do much more work than expected. For example, if each inner stream reads pages from a DB or HTTP, on Java 8 the remaining pages are requested even after the first match is found.
  • After a migration it goes the other way: inner streams with side effects (logging, a counter) now run less. If someone relied on that, the behavior changes.

Easy to check:

Stream.of("a", "b")
      .flatMap(s -> Stream.of(1, 2, 3).peek(i -> System.out.println(s + i)))
      .anyMatch(i -> i == 1);
// Java 10+: only a1. Java 8: a1 a2 a3

Something else to be careful about: even when flatMap short-circuits, if a stateful stage like sorted() comes after it, everything is still read. Also, for the inner stream to be stopped on Java 10+, it has to be lazy: if you loaded the whole list before turning it into list.stream(), short-circuiting saves nothing.