title: @Async with for loop in spring
body: <p>I have following scenario.</p>
  
  <ul>
  <li>there is some kind of daily calculation, which can be done retroactively for  months.</li>
  <li>it's very time consuming, involves lots of calculations</li>
  <li>no day is dependent on the result of any other day, every day is standalone.</li>
  <li>calculations will be triggered from web API</li>
  <li>all the results will be saved for later use</li>
  <li>all methods are void</li>
  </ul>
  
  <p>So, I was thinking about for loop that would calculate multiple days at time, since there is no need to know about results of other days, but i cant figure how to do this properly.</p>
  
  <p>where do I put the <code>@Async</code> annotation?</p>
  
  <p>method for JAX is as follows:</p>
  
  <pre><code>@POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Path("/calculated")
  public void calculated(String req,
                           final @Context SecurityContext securityContext,
                           final @Suspended AsyncResponse response2) {
  
      logger.info("calculating");
      ThymeDate thymeDate =  parseJSONDate(req);
  
      thymeNewDateRange.getDataForDateRange(thymeDate, null);
  
  }
  </code></pre>
  
  <p>this will send object that has date a and date b into <code>getDataForDateRange</code> method, which will then loop days between a and b.</p>
  
  <pre><code> public void iterateOverDays(ThymeDate thymeDate) {
          for (LocalDate date : new DateRange(thymeDate.getDate_a(), thymeDate.getDate_b())) {
               ControlService.dailyCalculation(date, null);
          }
  </code></pre>
  
  <p>and as stated before, <code>dailyCalculation</code> method is huge so i will not paste the code for it, but it is a void method with many calculations in it.</p>
  
  <p>I've tried to put <code>@Async</code> into <code>dailyCalculation</code> method, but application started to skip days and do multiple calculation on some days, seemingly randomly.</p>
  
  <p>I also tried to put it in JAX and for loop method, which lead to async not being used at all.</p>
  
  <p>i have following Executor in my AppConfig:</p>
  
  <pre><code>@Bean
  public Executor taskExecutor() {
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      executor.setCorePoolSize(4);
      executor.setMaxPoolSize(4);
      executor.setQueueCapacity(500);
      executor.setThreadNamePrefix("calc-thread-");
      executor.initialize();
      return executor;
  }
  </code></pre>