title: Spring @Async method spawning more threads: How to preserve request context
body: <p>In our Spring application we have the situation that we consumer several cloud-based REST endpoints to retrieve data that are combined into one single data object (let's call it <code>Employee.java</code>), which is then passed to the business logic.</p>
  
  <p>I would like to encapsulate all these calls into one method of a service bean, something like this:</p>
  
  <pre><code>@Service
  public class EmployeeService {
  
     public Employee retrieveEmployee(String id) {
        Employee e = new Employee();
        callRESTToFillWithBasicData(e);
        callRESTToFillWithExtendedData(e);
        callRESTToFillWithAdditionalData(e);
        return e;
     }
  }
  </code></pre>
  
  <p>As the REST calls are rather time consuming, we want to make this method asynchronous, so the application can do other stuff in the meantime.
  For additional difficulty, the methods in the service need access to request-scoped Spring beans. The problem is that Spring doesn't by default pass the request context to threads spawned through async methods. Therefore we've written a custom implementation of ThreadPoolTaskExecutor, similar to what is suggested <a href="https://stackoverflow.com/questions/23732089/how-to-enable-request-scope-in-async-task-executor">here</a>. The asynchronous code looks like this:</p>
  
  <pre><code>@Service
  public class EmployeeService {
  
     @Async("requestAwareTaskExecutor")
     public CompletableFuture&lt;Employee&gt; retrieveEmployee(String id) {
        Employee e = new Employee();
        callRESTToFillWithBasicData(e);
        callRESTToFillWithExtendedData(e);
        callRESTToFillWithAdditionalData(e);
        return CompletableFuture.completedFuture(e);
     }
  }
  </code></pre>
  
  <p>Now, to speed the whole thing up some more, we also want to parallelize the 3 REST calls in the method.
  This leaves us with some problems to solve:</p>
  
  <ul>
  <li><p>The problem is, we can't just put <code>@Async</code> on the <code>callRESTToFill...</code> methods, because method calls from one object to itself are not routed through the Spring proxy and thus not executed asynchronously.</p></li>
  <li><p>We also can't just wrap the method calls in <code>CompletableFuture.runAsync(...)</code>, because then the threads would, again, be unable to access request scoped beans.</p></li>
  <li><p>The last resort would be to have the request-aware Executor bean <code>@Autowired</code> into the service bean and pass it to all the <code>CompletableFuture</code> calls.</p></li>
  </ul>
  
  <p>But we don't feel that this is the Spring way to go. Directly using the Executor feels kind of superfluous, considering that we've already specified the executor bean in the <code>@Async</code> annotation.</p>
  
  <p>What would be the best practice here?</p>