title: @Async prevent a thread to continue until other thread have finished
body: <p>I have an application where for a certain number of times something needs to be calculated. This calculation function has the annotation @Async (from the Spring Framework), that makes it possible to run these calculations on 4 threads. The problem is that I need about 40000 of these calculations and I want to know the time between the start and end of all the calculations, so I see what time it is before and after the for-loop that calls the calculation functions. But now all the calculations are put in a queue, so the for loop finishes immediately and the time is something like 1 second, while it takes a couple of hours for the calculations to complete. I've tried setting a max queue size to about 100 (also good to reduce memory usage) but this is also no solution since I'll miss the last 100 calculations in the total time it takes. Is there a way to pause the executing code just after the for loop until all threads have finished doing their work, but still being able to use the @Async annotation?</p>
  
  <p>This is some code that illustrates the same problem:</p>
  
  <p>Executing class:</p>
  
  <pre><code>public class Foo {
      public void executeBlaALotOfTimes() {
          long before = System.currentTimeMillis();
  
          for (int i = 0; i&lt;40000; i++) {
              executeBla();
          }
  
          long after = System.currentTimeMillis(); 
  
          System.out.println("Time it took for a lot of bla to execute: " + (after - before) / 1000.0 + " seconds.");
      }
  }
  </code></pre>
  
  <p>And the class that performs the calculations:</p>
  
  <pre><code>@Service
  public class Bar {
      @Async
      public void executeBla() {
          System.out.println("Bla!");
      }
  }
  </code></pre>
  
  <p>This would result in the following output (assuming the code in Foo executes infinitely fast):</p>
  
  <pre>
  Time it took for a lot of bla to execute: 0.0 seconds.
  Bla!
  Bla!
  Bla!
  Bla!
  .
  .
  .
  etc
  </pre>