title: Why using parallel streams in static initializer leads to not stable deadlock
body: <p><strong>CAUTION:</strong> it is not a duplicate, please read topic <strong>сarefully</strong>
  <a href="https://stackoverflow.com/users/3448419/apangin">https://stackoverflow.com/users/3448419/apangin</a> quote:</p>
  
  <blockquote>
    <p>The real question is why the code sometimes works when it should not.
    The issue reproduces even without lambdas. This makes me think there
    might be a JVM bug.</p>
  </blockquote>
  
  <p>In the comments of <a href="https://stackoverflow.com/a/53709217/2674303">https://stackoverflow.com/a/53709217/2674303</a> I tried to find out reasons why code behaves differently from one start to another and participants of that discussion made me piece of of advice to create a separated topic.</p>
  
  <p>Let's consider following source code:</p>
  
  <pre><code>public class Test {
      static {
          System.out.println("static initializer: " + Thread.currentThread().getName());
  
          final long SUM = IntStream.range(0, 5)
                  .parallel()
                  .mapToObj(i -&gt; {
                      System.out.println("map: " + Thread.currentThread().getName() + " " + i);
                      return i;
                  })
                  .sum();
      }
  
      public static void main(String[] args) {
          System.out.println("Finished");
      }
  }
  </code></pre>
  
  <p>Sometimes(almost always) it leads to deadlock.</p>
  
  <p>Example of output:</p>
  
  <pre><code>static initializer: main
  map: main 2
  map: ForkJoinPool.commonPool-worker-3 4
  map: ForkJoinPool.commonPool-worker-3 3
  map: ForkJoinPool.commonPool-worker-2 0
  </code></pre>
  
  <p>But sometimes it finishes successfully(very rare):</p>
  
  <pre><code>static initializer: main
  map: main 2
  map: main 3
  map: ForkJoinPool.commonPool-worker-2 4
  map: ForkJoinPool.commonPool-worker-1 1
  map: ForkJoinPool.commonPool-worker-3 0
  Finished
  </code></pre>
  
  <p>or </p>
  
  <pre><code>static initializer: main
  map: main 2
  map: ForkJoinPool.commonPool-worker-2 0
  map: ForkJoinPool.commonPool-worker-1 1
  map: ForkJoinPool.commonPool-worker-3 4
  map: main 3
  </code></pre>
  
  <p>Could you explain that behaviour?</p>