Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8149614

Stream.flatmap...findAny does not short-circuit as expected

    XMLWordPrintable

    Details

      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 ----------

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: