title: java - Simple calculation takes longer in multi threads than in single thread
body: <p>I'm trying to understand how to take advantage of using multi threads. I wrote a simple program that increments the value of <code>i</code>, let's say, 400,000 times using two ways : a single threaded way (0 to 400,000) and a multiple threaded way (in my case, 4 times : 0 to 100,000) with the number of thread equal to <code>Runtime.getRuntime().availableProcessors()</code>.</p>
  
  <p>I'm surprised with the results I measured : the single threaded way is decidedly faster, sometimes 3 times faster. Here is my code :</p>
  
  <pre><code>public class Main {
      public static int LOOPS = 100000;
      private static ExecutorService executor=null;
  
      public static void main(String[] args) throws InterruptedException, ExecutionException {
  
          int procNb = Runtime.getRuntime().availableProcessors();
          long startTime;
          long endTime;
  
          executor = Executors.newFixedThreadPool(procNb);
          ArrayList&lt;Calculation&gt; c = new ArrayList&lt;Calculation&gt;();
  
          for (int i=0;i&lt;procNb;i++){
              c.add(new Calculation());
          }
  
          // Make parallel computations (4 in my case)
          startTime = System.currentTimeMillis();
          queryAll(c);
          endTime = System.currentTimeMillis();
  
          System.out.println("Computation time using " + procNb + " threads : " + (endTime - startTime) + "ms");
  
          startTime = System.currentTimeMillis();
          for (int i =0;i&lt;procNb*LOOPS;i++)
          {
  
          }
          endTime = System.currentTimeMillis();
          System.out.println("Computation time using main thread : " + (endTime - startTime) + "ms");
      }
  
      public static List&lt;Integer&gt; queryAll(List&lt;Calculation&gt; queries) throws InterruptedException, ExecutionException {
          List&lt;Future&lt;Integer&gt;&gt; futures = executor.invokeAll(queries);
          List&lt;Integer&gt; aggregatedResults = new ArrayList&lt;Integer&gt;();
          for (Future&lt;Integer&gt; future : futures) {
              aggregatedResults.add(future.get());
          }
          return aggregatedResults;
      }
  
  }
  
  class Calculation implements Callable&lt;Integer&gt; {
  
      @Override
      public Integer call() {
          int i;
          for (i=0;i&lt;Main.LOOPS;i++){
          }
          return i;
      }
  }
  </code></pre>
  
  <p>Console :</p>
  
  <p><code>Computation time using 4 threads : 10ms.
  </code>
  <code>Computation time using main thread : 3ms.</code></p>
  
  <p>Could anyone explain this ?</p>