title: Java 8 streams serial vs parallel performance
body: <p>On my machine, the program below prints:</p>
  
  <pre><code>OptionalLong[134043]
   PARALLEL took 127869 ms
  OptionalLong[134043]
   SERIAL took 60594 ms
  </code></pre>
  
  <p>It's not clear to my why executing the program in serial is faster than executing it in parallel.  I've given both programs <code>-Xms2g -Xmx2g</code> on an <code>8gb</code> box thats relatively quiet.  Can someone clarify whats going on?</p>
  
  <pre><code>import java.util.stream.LongStream;
  import java.util.stream.LongStream.Builder;
  
  public class Problem47 {
  
      public static void main(String[] args) {
  
          final long startTime = System.currentTimeMillis();
          System.out.println(LongStream.iterate(1, n -&gt; n + 1).parallel().limit(1000000).filter(n -&gt; fourConsecutives(n)).findFirst());
          final long endTime = System.currentTimeMillis();
          System.out.println(" PARALLEL took " +(endTime - startTime) + " ms");
  
          final long startTime2 = System.currentTimeMillis();
          System.out.println(LongStream.iterate(1, n -&gt; n + 1).limit(1000000).filter(n -&gt; fourConsecutives(n)).findFirst());
          final long endTime2 = System.currentTimeMillis();
          System.out.println(" SERIAL took " +(endTime2 - startTime2) + " ms");
      }
  
      static boolean fourConsecutives(final long n) {
          return distinctPrimeFactors(n).count() == 4 &amp;&amp;
                  distinctPrimeFactors(n + 1).count() == 4 &amp;&amp;
                  distinctPrimeFactors(n + 2).count() == 4 &amp;&amp;
                  distinctPrimeFactors(n + 3).count() == 4;
      }
  
      static LongStream distinctPrimeFactors(long number) {
          final Builder builder = LongStream.builder();
          final long limit = number / 2;
          long n = number;
          for (long i = 2; i &lt;= limit; i++) {
              while (n % i == 0) {
                  builder.accept(i);
                  n /= i;
              }
          }
          return builder.build().distinct();
      }
  
  }
  </code></pre>