title: Java - Calculate PI - Single vs Multi-Thread
body: <p>I have no clue why but my single thread code to calculate PI is much faster than multi. I'm using 500 Million points and for multi-thread 16 cores. With single CPU is fine and multi-thread all 16 Cores are 100% but it's slower...</p>
  
  <p>Any clue??</p>
  
  <p>Single</p>
  
  <pre><code>    public static double monteCarloMethodSequencialMethod(long points) {
      long inCircle = 0;
  
      for (long i = 0; i &lt; points; i++) {
  
          double x = Math.random();
          double y = Math.random();
  
          if(x * x + y * y &lt;= 1) inCircle++;
      }
  
      return 4.0 * inCircle / points;
  }
  </code></pre>
  
  <blockquote>
    <p>Sequencial Monte-Carlo estimated PI value : 3.141562496. Executed in 13432.927304 ms.</p>
  </blockquote>
  
  <p>Multi-Thread</p>
  
  <pre><code>    public double calculatePI() throws InterruptedException, ExecutionException {
  
      double sum = 0;
  
      List&lt;Future&lt;Double&gt;&gt; tasks = new ArrayList&lt;&gt;();
  
      ExecutorService executor = Executors.newFixedThreadPool(nProcessors);
  
      for (long i = 0; i &lt; points; i += points / nProcessors) {
          Future&lt;Double&gt; task = executor.submit(() -&gt; {
              long inCircle = 0;
              double val = 0;
  
              for(long k = 0; k &lt; points / nProcessors; k++) {
                  double x = Math.random();
                  double y = Math.random();
  
                  if(x * x + y * y &lt;= 1) inCircle++;
              }
              val = 4.0 * inCircle;
  
              return val;
          });
  
          tasks.add(task);
      }
  
      long pending = nProcessors;
      while(pending != 0) {
          for(Future&lt;Double&gt; future : tasks) {
              if(future.isDone()) {
                  sum += future.get();
                  pending--;
                  System.out.println(pending + " task are still pending");
              }
          }
      }       
  
      executor.shutdown();
  
      return sum / points;
  }
  </code></pre>
  
  <blockquote>
    <p>Concurrent Monte-Carlo estimated PI value : 3.141666048. Executed in 116236.812471 ms.</p>
  </blockquote>