1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util.stream;
  26 
  27 import java.util.Objects;
  28 import java.util.Spliterator;
  29 import java.util.function.IntFunction;
  30 import java.util.function.Supplier;
  31 
  32 /**
  33  * Abstract base class for "pipeline" classes, which are the core
  34  * implementations of the Stream interface and its primitive specializations.
  35  * Manages construction and evaluation of stream pipelines.
  36  *
  37  * <p>An {@code AbstractPipeline} represents an initial portion of a stream
  38  * pipeline, encapsulating a stream source and zero or more intermediate
  39  * operations.  The individual {@code AbstractPipeline} objects are often
  40  * referred to as <em>stages</em>, where each stage describes either the stream
  41  * source or an intermediate operation.
  42  *
  43  * <p>A concrete intermediate stage is generally built from an
  44  * {@code AbstractPipeline}, a shape-specific pipeline class which extends it
  45  * (e.g., {@code IntPipeline}) which is also abstract, and an operation-specific
  46  * concrete class which extends that.  {@code AbstractPipeline} contains most of
  47  * the mechanics of evaluating the pipeline, and implements methods that will be
  48  * used by the operation; the shape-specific classes add helper methods for
  49  * dealing with collection of results into the appropriate shape-specific
  50  * containers.
  51  *
  52  * <p>After chaining a new intermediate operation, or executing a terminal
  53  * operation, the stream is considered to be consumed, and no more intermediate
  54  * or terminal operations are permitted on this stream instance.
  55  *
  56  * <p>{@code AbstractPipeline} implements a number of methods that are
  57  * specified in {@link BaseStream}, though it does not implement
  58  * {@code BaseStream} directly.  Subclasses of {@code AbstractPipeline}
  59  * will generally implement {@code BaseStream}.
  60  *
  61  * @implNote
  62  * <p>For sequential streams, and parallel streams without
  63  * <a href="package-summary.html#StreamOps">stateful intermediate
  64  * operations</a>, parallel streams, pipeline evaluation is done in a single
  65  * pass that "jams" all the operations together.  For parallel streams with
  66  * stateful operations, execution is divided into segments, where each
  67  * stateful operations marks the end of a segment, and each segment is
  68  * evaluated separately and the result used as the input to the next
  69  * segment.  In all cases, the source data is not consumed until a terminal
  70  * operation begins.
  71  *
  72  * @param <E_IN>  Type of input elements.
  73  * @param <E_OUT> Type of output elements.
  74  * @param <S> Type of the subclass implementing {@code BaseStream}
  75  * @since 1.8
  76  */
  77 abstract class AbstractPipeline<E_IN, E_OUT, S extends BaseStream<E_OUT, S>>
  78         extends PipelineHelper<E_OUT> {
  79     /**
  80      * Backlink to the head of the pipeline chain (self if this is the source
  81      * stage)
  82      */
  83     private final AbstractPipeline sourceStage;
  84 
  85     /** The "upstream" pipeline, or null if this is the source stage */
  86     private final AbstractPipeline previousStage;
  87 
  88     /**
  89      * The operation flags for the intermediate operation represented by this
  90      * pipeline object
  91      */
  92     protected final int sourceOrOpFlags;
  93 
  94     /**
  95      * The next stage in the pipeline, or null if this is the last stage.
  96      * Effectively final at the point of linking to the next pipeline.
  97      */
  98     private AbstractPipeline nextStage;
  99 
 100     /**
 101      * The number of intermediate operations between this pipeline object
 102      * and the stream source if sequential, or the previous stateful if parallel.
 103      * Valid at the point of pipeline preparation for evaluation.
 104      */
 105     private int depth;
 106 
 107     /**
 108      * The combined source and operation flags for the source and all operations
 109      * up to and including the operation represented by this pipeline object.
 110      * Valid at the point of pipeline preparation for evaluation.
 111      */
 112     private int combinedFlags;
 113 
 114     /**
 115      * The source spliterator. Only valid for the head pipeline.
 116      * Before the pipeline is consumed if non-null then {@code sourceSupplier}
 117      * must be null. After the pipeline is consumed if non-null then is set to
 118      * null.
 119      */
 120     private Spliterator<?> sourceSpliterator;
 121     /**
 122      * The source supplier. Only valid for the head pipeline. Before the
 123      * pipeline is consumed if non-null then {@code sourceSpliterator} must be
 124      * null. After the pipeline is consumed if non-null then is set to null.
 125      */
 126     private Supplier<? extends Spliterator<?>> sourceSupplier;
 127 
 128     /** True if this pipeline has been linked or consumed */
 129     private boolean linkedOrConsumed;
 130 
 131     /**
 132      * True if there are any stateful ops in the pipeline; only valid for the
 133      * source stage.
 134      */
 135     private boolean sourceAnyStateful;
 136 
 137     /**
 138      * True if pipeline is parallel, otherwise the pipeline is sequential; only
 139      * valid for the source stage.
 140      */
 141     private boolean parallel;
 142 
 143     /**
 144      * Constructor for the head of a stream pipeline.
 145      *
 146      * @param source {@code Supplier<Spliterator>} describing the stream source
 147      * @param sourceFlags The source flags for the stream source, described in
 148      * {@link StreamOpFlag}
 149      * @param parallel True if the pipeline is parallel
 150      */
 151     AbstractPipeline(Supplier<? extends Spliterator<?>> source,
 152                      int sourceFlags, boolean parallel) {
 153         this.previousStage = null;
 154         this.sourceSupplier = source;
 155         this.sourceStage = this;
 156         this.sourceOrOpFlags = sourceFlags & StreamOpFlag.STREAM_MASK;
 157         // The following is an optimization of:
 158         // StreamOpFlag.combineOpFlags(sourceOrOpFlags, StreamOpFlag.INITIAL_OPS_VALUE);
 159         this.combinedFlags = (~(sourceOrOpFlags << 1)) & StreamOpFlag.INITIAL_OPS_VALUE;
 160         this.depth = 0;
 161         this.parallel = parallel;
 162     }
 163 
 164     /**
 165      * Constructor for the head of a stream pipeline.
 166      *
 167      * @param source {@code Spliterator} describing the stream source
 168      * @param sourceFlags The source flags for the stream source, described in
 169      * {@link StreamOpFlag}
 170      * @param parallel True if the pipeline is parallel
 171      */
 172     AbstractPipeline(Spliterator<?> source,
 173                      int sourceFlags, boolean parallel) {
 174         this.previousStage = null;
 175         this.sourceSpliterator = source;
 176         this.sourceStage = this;
 177         this.sourceOrOpFlags = sourceFlags & StreamOpFlag.STREAM_MASK;
 178         // The following is an optimization of:
 179         // StreamOpFlag.combineOpFlags(sourceOrOpFlags, StreamOpFlag.INITIAL_OPS_VALUE);
 180         this.combinedFlags = (~(sourceOrOpFlags << 1)) & StreamOpFlag.INITIAL_OPS_VALUE;
 181         this.depth = 0;
 182         this.parallel = parallel;
 183     }
 184 
 185     /**
 186      * Constructor for appending an intermediate operation stage onto an
 187      * existing pipeline.
 188      *
 189      * @param previousStage the upstream pipeline stage
 190      * @param opFlags the operation flags for the new stage, described in
 191      * {@link StreamOpFlag}
 192      */
 193     AbstractPipeline(AbstractPipeline<?, E_IN, ?> previousStage,
 194                      int opFlags) {
 195         if (previousStage.linkedOrConsumed)
 196             throw new IllegalStateException("stream has already been operated upon");
 197         previousStage.linkedOrConsumed = true;
 198         previousStage.nextStage = this;
 199 
 200         this.previousStage = previousStage;
 201         this.sourceOrOpFlags = opFlags & StreamOpFlag.OP_MASK;
 202         this.combinedFlags = StreamOpFlag.combineOpFlags(opFlags, previousStage.combinedFlags);
 203         this.sourceStage = previousStage.sourceStage;
 204         if (opIsStateful())
 205             sourceStage.sourceAnyStateful = true;
 206         this.depth = previousStage.depth + 1;
 207     }
 208 
 209 
 210     // Terminal evaluation methods
 211 
 212     /**
 213      * Evaluate the pipeline with a terminal operation to produce a result.
 214      *
 215      * @param terminalOp the terminal operation to be applied to the pipeline.
 216      * @param <R> the type of result
 217      * @return the result
 218      */
 219     final <R> R evaluate(TerminalOp<E_OUT, R> terminalOp) {
 220         assert getOutputShape() == terminalOp.inputShape();
 221         if (linkedOrConsumed)
 222             throw new IllegalStateException("stream has already been operated upon");
 223         linkedOrConsumed = true;
 224 
 225         return isParallel()
 226                ? (R) terminalOp.evaluateParallel(this, sourceSpliterator(terminalOp.getOpFlags()))
 227                : (R) terminalOp.evaluateSequential(this, sourceSpliterator(terminalOp.getOpFlags()));
 228     }
 229 
 230     /**
 231      * Collect the elements output from the pipeline stage.
 232      *
 233      * @param generator the array generator to be used to create array instances
 234      * @return a flat array-backed Node that holds the collected output elements
 235      */
 236     final Node<E_OUT> evaluateToArrayNode(IntFunction<E_OUT[]> generator) {
 237         if (linkedOrConsumed)
 238             throw new IllegalStateException("stream has already been operated upon");
 239         linkedOrConsumed = true;
 240 
 241         // If the last intermediate operation is stateful then
 242         // evaluate directly to avoid an extra collection step
 243         if (isParallel() && previousStage != null && opIsStateful()) {
 244             return opEvaluateParallel(previousStage, previousStage.sourceSpliterator(0), generator);
 245         }
 246         else {
 247             return evaluate(sourceSpliterator(0), true, generator);
 248         }
 249     }
 250 
 251     /**
 252      * Gets the source stage spliterator if this pipeline stage is the source
 253      * stage.  The pipeline is consumed after this method is called and
 254      * returns successfully.
 255      *
 256      * @return the source stage spliterator
 257      * @throws IllegalStateException if this pipeline stage is not the source
 258      *         stage.
 259      */
 260     final Spliterator<E_OUT> sourceStageSpliterator() {
 261         if (this != sourceStage)
 262             throw new IllegalStateException();
 263 
 264         if (linkedOrConsumed)
 265             throw new IllegalStateException("stream has already been operated upon");
 266         linkedOrConsumed = true;
 267 
 268         if (sourceStage.sourceSpliterator != null) {
 269             Spliterator<E_OUT> s = sourceStage.sourceSpliterator;
 270             sourceStage.sourceSpliterator = null;
 271             return s;
 272         }
 273         else if (sourceStage.sourceSupplier != null) {
 274             Spliterator<E_OUT> s = (Spliterator<E_OUT>) sourceStage.sourceSupplier.get();
 275             sourceStage.sourceSupplier = null;
 276             return s;
 277         }
 278         else {
 279             throw new IllegalStateException("source already consumed");
 280         }
 281     }
 282 
 283     // BaseStream
 284 
 285     /** Implements {@link BaseStream#sequential()} */
 286     public final S sequential() {
 287         sourceStage.parallel = false;
 288         return (S) this;
 289     }
 290 
 291     /** Implements {@link BaseStream#parallel()} */
 292     public final S parallel() {
 293         sourceStage.parallel = true;
 294         return (S) this;
 295     }
 296 
 297     // Primitive specialization use co-variant overrides, hence is not final
 298     /** Implements {@link BaseStream#spliterator()} */
 299     public Spliterator<E_OUT> spliterator() {
 300         if (linkedOrConsumed)
 301             throw new IllegalStateException("stream has already been operated upon");
 302         linkedOrConsumed = true;
 303 
 304         if (this == sourceStage) {
 305             if (sourceStage.sourceSpliterator != null) {
 306                 Spliterator<E_OUT> s = sourceStage.sourceSpliterator;
 307                 sourceStage.sourceSpliterator = null;
 308                 return s;
 309             }
 310             else if (sourceStage.sourceSupplier != null) {
 311                 Supplier<Spliterator<E_OUT>> s = sourceStage.sourceSupplier;
 312                 sourceStage.sourceSupplier = null;
 313                 return lazySpliterator(s);
 314             }
 315             else {
 316                 throw new IllegalStateException("source already consumed");
 317             }
 318         }
 319         else {
 320             return wrap(this, () -> sourceSpliterator(0), isParallel());
 321         }
 322     }
 323 
 324     /** Implements {@link BaseStream#isParallel()} */
 325     public final boolean isParallel() {
 326         return sourceStage.parallel;
 327     }
 328 
 329 
 330     /**
 331      * Returns the composition of stream flags of the stream source and all
 332      * intermediate operations.
 333      *
 334      * @return the composition of stream flags of the stream source and all
 335      *         intermediate operations
 336      * @see StreamOpFlag
 337      */
 338     final int getStreamFlags() {
 339         return StreamOpFlag.toStreamFlags(combinedFlags);
 340     }
 341 
 342     /**
 343      * Prepare the pipeline for a parallel execution.  As the pipeline is built,
 344      * the flags and depth indicators are set up for a sequential execution.
 345      * If the execution is parallel, and there are any stateful operations, then
 346      * some of these need to be adjusted, as well as adjusting for flags from
 347      * the terminal operation (such as back-propagating UNORDERED).
 348      * Need not be called for a sequential execution.
 349      * @param terminalFlags Operation flags for the terminal operation
 350      */
 351     private void parallelPrepare(int terminalFlags) {
 352         AbstractPipeline backPropagationHead = sourceStage;
 353         if (sourceStage.sourceAnyStateful) {
 354             int depth = 1;
 355             for (AbstractPipeline u = sourceStage, p = sourceStage.nextStage;
 356                  p != null;
 357                  u = p, p = p.nextStage) {
 358                 int thisOpFlags = p.sourceOrOpFlags;
 359                 if (p.opIsStateful()) {
 360                     // If the stateful operation is a short-circuit operation
 361                     // then move the back propagation head forwards
 362                     // NOTE: there are no size-injecting ops
 363                     if (StreamOpFlag.SHORT_CIRCUIT.isKnown(thisOpFlags)) {
 364                         backPropagationHead = p;
 365                     }
 366 
 367                     depth = 0;
 368                     // The following injects size, it is equivalent to:
 369                     // StreamOpFlag.combineOpFlags(StreamOpFlag.IS_SIZED, p.combinedFlags);
 370                     thisOpFlags = (thisOpFlags & ~StreamOpFlag.NOT_SIZED) | StreamOpFlag.IS_SIZED;
 371                 }
 372                 p.depth = depth++;
 373                 p.combinedFlags = StreamOpFlag.combineOpFlags(thisOpFlags, u.combinedFlags);
 374             }
 375         }
 376 
 377         // Apply the upstream terminal flags
 378         if (terminalFlags != 0) {
 379             int upstreamTerminalFlags = terminalFlags & StreamOpFlag.UPSTREAM_TERMINAL_OP_MASK;
 380             for (AbstractPipeline p = backPropagationHead; p.nextStage != null; p = p.nextStage) {
 381                 p.combinedFlags = StreamOpFlag.combineOpFlags(upstreamTerminalFlags, p.combinedFlags);
 382             }
 383 
 384             combinedFlags = StreamOpFlag.combineOpFlags(terminalFlags, combinedFlags);
 385         }
 386     }
 387 
 388     /**
 389      * Get the source spliterator for this pipeline stage.  For a sequential or
 390      * stateless parallel pipeline, this is the source spliterator.  For a
 391      * stateful parallel pipeline, this is a spliterator describing the results
 392      * of all computations up to and including the most recent stateful
 393      * operation.
 394      */
 395     private Spliterator<?> sourceSpliterator(int terminalFlags) {
 396         // Get the source spliterator of the pipeline
 397         Spliterator<?> spliterator = null;
 398         if (sourceStage.sourceSpliterator != null) {
 399             spliterator = sourceStage.sourceSpliterator;
 400             sourceStage.sourceSpliterator = null;
 401         }
 402         else if (sourceStage.sourceSupplier != null) {
 403             spliterator = (Spliterator<?>) sourceStage.sourceSupplier.get();
 404             sourceStage.sourceSupplier = null;
 405         }
 406         else {
 407             throw new IllegalStateException("source already consumed");
 408         }
 409 
 410         if (isParallel()) {
 411             // @@@ Merge parallelPrepare with the loop below and use the
 412             //     spliterator characteristics to determine if SIZED
 413             //     should be injected
 414             parallelPrepare(terminalFlags);
 415 
 416             // Adapt the source spliterator, evaluating each stateful op
 417             // in the pipeline up to and including this pipeline stage
 418             for (AbstractPipeline u = sourceStage, p = sourceStage.nextStage, e = this;
 419                  u != e;
 420                  u = p, p = p.nextStage) {
 421 
 422                 if (p.opIsStateful()) {
 423                     spliterator = p.opEvaluateParallelLazy(u, spliterator);
 424                 }
 425             }
 426         }
 427         else if (terminalFlags != 0)  {
 428             combinedFlags = StreamOpFlag.combineOpFlags(terminalFlags, combinedFlags);
 429         }
 430 
 431         return spliterator;
 432     }
 433 
 434 
 435     // PipelineHelper
 436 
 437     @Override
 438     final <P_IN> long exactOutputSizeIfKnown(Spliterator<P_IN> spliterator) {
 439         return StreamOpFlag.SIZED.isKnown(getStreamAndOpFlags()) ? spliterator.getExactSizeIfKnown() : -1;
 440     }
 441 
 442     @Override
 443     final <P_IN, S extends Sink<E_OUT>> S wrapAndCopyInto(S sink, Spliterator<P_IN> spliterator) {
 444         copyInto(wrapSink(Objects.requireNonNull(sink)), spliterator);
 445         return sink;
 446     }
 447 
 448     @Override
 449     final <P_IN> void copyInto(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator) {
 450         Objects.requireNonNull(wrappedSink);
 451 
 452         if (!StreamOpFlag.SHORT_CIRCUIT.isKnown(getStreamAndOpFlags())) {
 453             wrappedSink.begin(spliterator.getExactSizeIfKnown());
 454             spliterator.forEachRemaining(wrappedSink);
 455             wrappedSink.end();
 456         }
 457         else {
 458             copyIntoWithCancel(wrappedSink, spliterator);
 459         }
 460     }
 461 
 462     @Override
 463     final <P_IN> void copyIntoWithCancel(Sink<P_IN> wrappedSink, Spliterator<P_IN> spliterator) {
 464         AbstractPipeline p = AbstractPipeline.this;
 465         while (p.depth > 0) {
 466             p = p.previousStage;
 467         }
 468         wrappedSink.begin(spliterator.getExactSizeIfKnown());
 469         p.forEachWithCancel(spliterator, wrappedSink);
 470         wrappedSink.end();
 471     }
 472 
 473     @Override
 474     final int getStreamAndOpFlags() {
 475         return combinedFlags;
 476     }
 477 
 478     final boolean isOrdered() {
 479         return StreamOpFlag.ORDERED.isKnown(combinedFlags);
 480     }
 481 
 482     @Override
 483     final <P_IN> Sink<P_IN> wrapSink(Sink<E_OUT> sink) {
 484         Objects.requireNonNull(sink);
 485 
 486         for (AbstractPipeline p=AbstractPipeline.this; p.depth > 0; p=p.previousStage) {
 487             sink = p.opWrapSink(p.previousStage.combinedFlags, sink);
 488         }
 489         return (Sink<P_IN>) sink;
 490     }
 491 
 492     @Override
 493     @SuppressWarnings("unchecked")
 494     final <P_IN> Node<E_OUT> evaluate(Spliterator<P_IN> spliterator,
 495                                       boolean flatten,
 496                                       IntFunction<E_OUT[]> generator) {
 497         if (isParallel()) {
 498             // @@@ Optimize if op of this pipeline stage is a stateful op
 499             return evaluateToNode(this, spliterator, flatten, generator);
 500         }
 501         else {
 502             Node.Builder<E_OUT> nb = makeNodeBuilder(
 503                     exactOutputSizeIfKnown(spliterator), generator);
 504             return wrapAndCopyInto(nb, spliterator).build();
 505         }
 506     }
 507 
 508 
 509     // Shape-specific abstract methods, implemented by XxxPipeline classes
 510 
 511     /**
 512      * Get the output shape of the pipeline.  If the pipeline is the head,
 513      * then it's output shape corresponds to the shape of the source.
 514      * Otherwise, it's output shape corresponds to the output shape of the
 515      * associated operation.
 516      * @return the output shape
 517      */
 518     abstract StreamShape getOutputShape();
 519 
 520     /**
 521      * Collect elements output from a pipeline into a Node that holds elements
 522      * of this shape.
 523      *
 524      * @param helper the pipeline helper describing the pipeline stages
 525      * @param spliterator the source spliterator
 526      * @param flattenTree true if the returned node should be flattened
 527      * @param generator the array generator
 528      * @return a Node holding the output of the pipeline
 529      */
 530     abstract <P_IN> Node<E_OUT> evaluateToNode(PipelineHelper<E_OUT> helper,
 531                                                Spliterator<P_IN> spliterator,
 532                                                boolean flattenTree,
 533                                                IntFunction<E_OUT[]> generator);
 534 
 535     /**
 536      * Create a spliterator that wraps a source spliterator, compatible with
 537      * this stream shape, and operations associated with a {@link
 538      * PipelineHelper}.
 539      *
 540      * @param ph the pipeline helper describing the pipeline stages
 541      * @param supplier the supplier of a spliterator
 542      * @return a wrapping spliterator compatible with this shape
 543      */
 544     abstract <P_IN> Spliterator<E_OUT> wrap(PipelineHelper<E_OUT> ph,
 545                                             Supplier<Spliterator<P_IN>> supplier,
 546                                             boolean isParallel);
 547 
 548     /**
 549      * Create a lazy spliterator that wraps and obtains the supplied the
 550      * spliterator when a method is invoked on the lazy spliterator.
 551      * @param supplier the supplier of a spliterator
 552      */
 553     abstract Spliterator<E_OUT> lazySpliterator(Supplier<? extends Spliterator<E_OUT>> supplier);
 554 
 555     /**
 556      * Traverse the elements of a spliterator compatible with this stream shape,
 557      * pushing those elements into a sink.   If the sink requests cancellation,
 558      * no further elements will be pulled or pushed.
 559      * @param spliterator the spliterator to pull elements from
 560      * @param sink the sink to push elements to
 561      */
 562     abstract void forEachWithCancel(Spliterator<E_OUT> spliterator, Sink<E_OUT> sink);
 563 
 564     /**
 565      * Make a node builder compatible with this stream shape.
 566      *
 567      * @param exactSizeIfKnown if >=0, then a node builder will be created that
 568      * has a fixed capacity of at most sizeIfKnown elements. If < 0, then the
 569      * node builder has an unfixed capacity. A fixed capacity node builder will
 570      * throw exceptions if an element is added after builder has reached
 571      * capacity, or is built before the builder has reached capacity.
 572      * @param generator the array generator to be used to create instances of a
 573      * T[] array. For implementations supporting primitive nodes, this parameter
 574      * may be ignored.
 575      * @return a node builder
 576      */
 577     abstract Node.Builder<E_OUT> makeNodeBuilder(long exactSizeIfKnown,
 578                                                  IntFunction<E_OUT[]> generator);
 579 
 580 
 581     // Op-specific abstract methods, implemented by the operation class
 582 
 583     /**
 584      * Returns whether this operation is stateful or not.  If it is stateful,
 585      * then the method
 586      * {@link #opEvaluateParallel(PipelineHelper, java.util.Spliterator, java.util.function.IntFunction)}
 587      * must be overridden.
 588      *
 589      * @implSpec The default implementation returns {@code false}.
 590      * @return {@code true} if this operation is stateful
 591      */
 592     abstract boolean opIsStateful();
 593 
 594     /**
 595      * Accepts a {@code Sink} which will receive the results of this operation,
 596      * and return a {@code Sink} which accepts elements of the input type of
 597      * this operation and which performs the operation, passing the results to
 598      * the provided {@code Sink}.
 599      *
 600      * @apiNote
 601      * <p>The implementation may use the {@code flags} parameter to optimize the
 602      * sink wrapping.  For example, if the input is already {@code DISTINCT},
 603      * the implementation for the {@code Stream#distinct()} method could just
 604      * return the sink it was passed.
 605      *
 606      * @param flags The combined stream and operation flags up to, but not
 607      *        including, this operation
 608      * @param sink sink to which elements should be sent after processing
 609      * @return a sink which accepts elements, perform the operation upon
 610      *         each element, and passes the results (if any) to the provided
 611      *         {@code Sink}.
 612      */
 613     abstract Sink<E_IN> opWrapSink(int flags, Sink<E_OUT> sink);
 614 
 615     /**
 616      * Performs a parallel evaluation of the operation using the specified
 617      * {@code PipelineHelper} which describes the upstream intermediate
 618      * operations.  Only called on stateful operations.  If {@link
 619      * #opIsStateful()} returns true then implementations must override the
 620      * default implementation.
 621      * @implSpec The default implementation always throw
 622      * {@code UnsupportedOperationException}.
 623      *
 624      * @param helper the pipeline helper describing the pipeline stages
 625      * @param spliterator the source {@code Spliterator}
 626      * @param generator the array generator
 627      * @return a {@code Node} describing the result of the evaluation
 628      */
 629     <P_IN> Node<E_OUT> opEvaluateParallel(PipelineHelper<E_OUT> helper,
 630                                           Spliterator<P_IN> spliterator,
 631                                           IntFunction<E_OUT[]> generator) {
 632         throw new UnsupportedOperationException("Parallel evaluation is not supported");
 633     }
 634 
 635     /**
 636      * Returns a {@code Spliterator} describing a parallel evaluation of the
 637      * operation, using the specified {@code PipelineHelper} which describes the
 638      * upstream intermediate operations.  Only called on stateful operations.
 639      * It is not necessary (though acceptable) to do a full computation of the
 640      * result here; it is preferable, if possible, to describe the result via a
 641      * lazily evaluated spliterator.
 642      *
 643      * @param helper the pipeline helper
 644      * @param spliterator the source {@code Spliterator}
 645      * @return a {@code Spliterator} describing the result of the evaluation
 646      * @implSpec The default implementation behaves as if:
 647      * <pre>{@code
 648      *     return evaluateParallel(helper, i -> (E_OUT[]) new
 649      * Object[i]).spliterator();
 650      * }</pre>
 651      * and is suitable for implementations that cannot do better than a full
 652      * synchronous evaluation.
 653      */
 654     <P_IN> Spliterator<E_OUT> opEvaluateParallelLazy(PipelineHelper<E_OUT> helper,
 655                                                      Spliterator<P_IN> spliterator) {
 656         return opEvaluateParallel(helper, spliterator, i -> (E_OUT[]) new Object[i]).spliterator();
 657     }
 658 }