title: How to chain completable futures
body: <p>I have three functions <code>updateFieldFromCollection1()</code>, <code>insertFromColletion1ToCollection2()</code> and <code>deleteFromCollection1()</code> now.</p>
  
  <p>These calls aren't as such dependent on each other but when I want to chain them in <em>completableFuture</em> they have to run one after the other in the given order. </p>
  
  <pre><code>update-&gt; insert -&gt; delete
  </code></pre>
  
  <p>The calls don't return anything so i am using <em>runAsync</em> and <em>thenRun</em> methods of <em>completableFuture</em>. And have chained them accordingly. I am iterating on msgIds which is a list of strings.</p>
  
  <pre><code>msgIds.stream().forEach(msgId -&gt; CompletableFuture.runAsync(() -&gt;  
   {updateFieldFromCollection1()}).thenRun(() -&gt; 
   {insertFromColletion1ToCollection2()}).thenRun(() -&gt;  
   {deleteFromCollection1()}));
  </code></pre>
  
  <p>The above code works (update-> insert -> delete are done) but throws exception like duplicateKey and bulkwrite. I am sure that the problem comes because another thread is starting before the previous thread completes its task. I want them to run asynchronously but I want to discipline the threads by avoiding conflicts.<br>
  I am not sure where I need to tweak the code.</p>