title: Understanding the main loop in Streams API's ForEachTask
body: <p>It seems that the centerpiece of Java Streams' parallelization is the <code>ForEachTask</code>. Understanding its logic appears to be essential to acquiring the mental model necessary to anticipate the concurrent behavior of client code written against the Streams API. Yet I find my anticipations contradicted by the actual behavior.</p>
  <p>For reference, here is the key <code>compute()</code> method (<code>java/util/streams/ForEachOps.java:253</code>):</p>
  <pre><code>public void compute() {
    Spliterator&lt;S&gt; rightSplit = spliterator, leftSplit;
    long sizeEstimate = rightSplit.estimateSize(), sizeThreshold;
    if ((sizeThreshold = targetSize) == 0L)
      targetSize = sizeThreshold = AbstractTask.suggestTargetSize(sizeEstimate);
    boolean isShortCircuit = StreamOpFlag.SHORT_CIRCUIT.isKnown(helper.getStreamAndOpFlags());
    boolean forkRight = false;
    Sink&lt;S&gt; taskSink = sink;
    ForEachTask&lt;S, T&gt; task = this;
    while (!isShortCircuit || !taskSink.cancellationRequested()) {
      if (sizeEstimate &lt;= sizeThreshold ||
          (leftSplit = rightSplit.trySplit()) == null) {
        task.helper.copyInto(taskSink, rightSplit);
        break;
      }
      ForEachTask&lt;S, T&gt; leftTask = new ForEachTask&lt;&gt;(task, leftSplit);
      task.addToPendingCount(1);
      ForEachTask&lt;S, T&gt; taskToFork;
      if (forkRight) {
        forkRight = false;
        rightSplit = leftSplit;
        taskToFork = task;
        task = leftTask;
      }
      else {
        forkRight = true;
        taskToFork = leftTask;
      }
      taskToFork.fork();
      sizeEstimate = rightSplit.estimateSize();
    }
    task.spliterator = null;
    task.propagateCompletion();
  }
  </code></pre>
  <p>On a high level of description, the main loop keeps breaking down the spliterator, alternately forking off the processing of the chunk and processing it inline, until the spliterator refuses to split further or the remaining size is below the computed threshold.</p>
  <p>Now consider the above algorithm in the case of unsized streams, where the whole is not being split into roughly equal halves; instead chunks of predetermined size are being repeatedly taken from the head of the stream. In this case the &quot;suggested target size&quot; of the chunk is abnormally large, which basically means that the chunks are never re-split into smaller ones.</p>
  <p>The algorithm would therefore appear to alternately fork off one chunk, then process one inline. If each chunk takes the same time to process, this should result in no more than two cores being used. However, the actual behavior is that all four cores on my machine are occupied. Obviously, I am missing an important piece of the puzzle with that algorithm.</p>
  <p>What is it that I'm missing?</p>
  <hr />
  <h2>Appendix: test code</h2>
  <p>Here is a piece of self-contained code which may be used to test the behavior which is the subject of this question:</p>
  <pre><code>package test;
  
  import static java.util.concurrent.TimeUnit.NANOSECONDS;
  import static java.util.concurrent.TimeUnit.SECONDS;
  import static test.FixedBatchSpliteratorWrapper.withFixedSplits;
  
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.nio.file.Files;
  import java.nio.file.Path;
  import java.nio.file.Paths;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  import java.util.concurrent.atomic.AtomicLong;
  
  public class Parallelization {
    static final AtomicLong totalTime = new AtomicLong();
    static final ExecutorService pool = Executors.newFixedThreadPool(4);
  
    public static void main(String[] args) throws IOException {
      final long start = System.nanoTime();
      final Path inputPath = createInput();
      System.out.println(&quot;Start processing&quot;);
      try (PrintWriter w = new PrintWriter(Files.newBufferedWriter(Paths.get(&quot;output.txt&quot;)))) {
        withFixedSplits(Files.newBufferedReader(inputPath).lines(), 200).map(Parallelization::processLine)
        .forEach(w::println);
      }
      final double cpuTime = totalTime.get(), realTime = System.nanoTime() - start;
      final int cores = Runtime.getRuntime().availableProcessors();
      System.out.println(&quot;          Cores: &quot; + cores);
      System.out.format(&quot;       CPU time: %.2f s\n&quot;, cpuTime / SECONDS.toNanos(1));
      System.out.format(&quot;      Real time: %.2f s\n&quot;, realTime / SECONDS.toNanos(1));
      System.out.format(&quot;CPU utilization: %.2f%%&quot;, 100.0 * cpuTime / realTime / cores);
    }
    private static String processLine(String line) {
      final long localStart = System.nanoTime();
      double ret = 0;
      for (int i = 0; i &lt; line.length(); i++)
        for (int j = 0; j &lt; line.length(); j++)
          ret += Math.pow(line.charAt(i), line.charAt(j) / 32.0);
      final long took = System.nanoTime() - localStart;
      totalTime.getAndAdd(took);
      return NANOSECONDS.toMillis(took) + &quot; &quot; + ret;
    }
    private static Path createInput() throws IOException {
      final Path inputPath = Paths.get(&quot;input.txt&quot;);
      try (PrintWriter w = new PrintWriter(Files.newBufferedWriter(inputPath))) {
        for (int i = 0; i &lt; 6_000; i++) {
          final String text = String.valueOf(System.nanoTime());
          for (int j = 0; j &lt; 20; j++)
            w.print(text);
          w.println();
        }
      }
      return inputPath;
    }
  }
  </code></pre>
  <hr />
  <pre><code>package test;
  
  import static java.util.Spliterators.spliterator;
  import static java.util.stream.StreamSupport.stream;
  
  import java.util.Comparator;
  import java.util.Spliterator;
  import java.util.function.Consumer;
  import java.util.stream.Stream;
  
  public class FixedBatchSpliteratorWrapper&lt;T&gt; implements Spliterator&lt;T&gt; {
    private final Spliterator&lt;T&gt; spliterator;
    private final int batchSize;
    private final int characteristics;
    private long est;
  
    public FixedBatchSpliteratorWrapper(Spliterator&lt;T&gt; toWrap, long est, int batchSize) {
      final int c = toWrap.characteristics();
      this.characteristics = (c &amp; SIZED) != 0 ? c | SUBSIZED : c;
      this.spliterator = toWrap;
      this.batchSize = batchSize;
      this.est = est;
    }
    public FixedBatchSpliteratorWrapper(Spliterator&lt;T&gt; toWrap, int batchSize) {
      this(toWrap, toWrap.estimateSize(), batchSize);
    }
  
    public static &lt;T&gt; Stream&lt;T&gt; withFixedSplits(Stream&lt;T&gt; in, int batchSize) {
      return stream(new FixedBatchSpliteratorWrapper&lt;&gt;(in.spliterator(), batchSize), true);
    }
  
    @Override public Spliterator&lt;T&gt; trySplit() {
      final HoldingConsumer&lt;T&gt; holder = new HoldingConsumer&lt;&gt;();
      if (!spliterator.tryAdvance(holder)) return null;
      final Object[] a = new Object[batchSize];
      int j = 0;
      do a[j] = holder.value; while (++j &lt; batchSize &amp;&amp; tryAdvance(holder));
      if (est != Long.MAX_VALUE) est -= j;
      return spliterator(a, 0, j, characteristics());
    }
    @Override public boolean tryAdvance(Consumer&lt;? super T&gt; action) {
      return spliterator.tryAdvance(action);
    }
    @Override public void forEachRemaining(Consumer&lt;? super T&gt; action) {
      spliterator.forEachRemaining(action);
    }
    @Override public Comparator&lt;? super T&gt; getComparator() {
      if (hasCharacteristics(SORTED)) return null;
      throw new IllegalStateException();
    }
    @Override public long estimateSize() { return est; }
    @Override public int characteristics() { return characteristics; }
  
    static final class HoldingConsumer&lt;T&gt; implements Consumer&lt;T&gt; {
      Object value;
      @Override public void accept(T value) { this.value = value; }
    }
  }
  </code></pre>