title: CompletableFuture to make webservice calls and save when everything is done
body: <p>I have a list of sessions that I have to call a webservice to set some property on each session.</p>
  
  <p>I am trying to call webservice using async process and use completablefuture for it so that when it is all done, I can save them all in db.</p>
  
  <p>How can I do this? So far, my code is as follows, it doesn't work.</p>
  
  <pre><code>sessions.stream()
          .forEach(s -&gt; CompletableFuture.runAsync(() -&gt; webServiceCall(s), executor));
  sessionService.saveAll(sessions);
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>I came up with this solution, not sure if this is the correct way of doing it.</p>
  
  <pre><code>List&lt;CompletableFuture&lt;Void&gt;&gt; futures = sessions.stream()
              .map(s -&gt; CompletableFuture.runAsync(() -&gt; webServiceCall(s), executor))
              .collect(Collectors.toList());
          CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                          .join();
          sessionService.saveAll(sessions);
  </code></pre>
  
  <p>I am using join to make sure it waits for response to return before saving sessions</p>