JDK-8149614 : Stream.flatmap...findAny does not short-circuit as expected
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util.stream
  • Affected Version: 8u66,9
  • Priority: P3
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic
  • CPU: generic
  • Submitted: 2016-02-10
  • Updated: 2016-03-03
  • Resolved: 2016-02-11
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :


A DESCRIPTION OF THE PROBLEM :
stream.flatMap(f).peek(c).findAny() does not display the expected short-circuiting behaviour. The consumer c is executed for every element of the stream output by f, when the expectation is it should only be executed once for non-parallel streams. This affects not just peek, but all stream operations.

This is problematic when intermediate operations are side-effectful, as they will be executed more often than expected, and when the flatmap produces an infinite stream, as the stream execution will not terminate.

Further discussion and examples exist at https://stackoverflow.com/questions/29229373/why-filter-after-flatmap-is-not-completely-lazy-in-java-streams


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
    @Test
    public void flatMapStreamIsLazy() {
        AtomicInteger peeks = new AtomicInteger();
        Stream.of(1)
              .flatMap(n -> Stream.of(n, n + 1))
              .peek(n -> peeks.incrementAndGet())
              .findAny();
        assertEquals(1, peeks.get()); // FAILS!
    }
---------- END SOURCE ----------


Comments
Ran the attached test case in: JDK 8u66 - Fail JDK 8u72 - Fail JDK 9ea -Fail
11-02-2016