title: CompletableFuture injection from the inside
body: <p>Is it possible to <em>inject</em> a <code>CompletableFuture</code> in a <code>CompletableFuture</code> chain from <em>the inside</em>?</p>
  
  <p>I'm working with a function like this:</p>
  
  <pre><code>public CompletableFuture&lt;Boolean&gt; getFutureOfMyLongRunningTask() {
      CompletableFuture&lt;Boolean&gt; future = CompletableFuture.supplyAsync(() -&gt; {
          // ... Some processing here ...
          if (somecondition failed)
              return false; // Task failed!
  
          return true; // OK
      }).thenApplyAsync((Boolean result) -&gt; {
          if (!result) // check of previous stage fail
              return false;
  
          // ... Some processing here ...
  
          if (!some condition satisfied) {
              // This is where I want the injection to happen. 
              // This stage should be suspended and a new stage should be injected between this point and the next stage.
          }
  
          return true; // OK
      }).thenApplyAsync((Boolean result) -&gt; {
          if (!result) // check of previous stage fail
              return false;
  
          // ... Some processing here ...
  
          return true; // OK
      });
  
      // This is the result we have to wait for.
      return future;
  }
  </code></pre>
  
  <p>At the injection point <code>if (!some condition satisfied)</code>, I'd like to run a query that (say) takes 5 seconds to execute and retrieve some data needed by the final stage. I don't want to block the thread for 5 seconds, eg make the query synchronous inside the <code>if</code>, I want it to run asynchronous, and when the results are back go straight to the next stage. The problem I'm having is that the condition is known only <em>inside</em> the chain.</p>
  
  <p>Anyone have ideas on this? </p>
  
  <hr>
  
  <p><strong>EDIT</strong></p>
  
  <p>I'll try to clarify the question. I originally <a href="https://stackoverflow.com/q/40455394/6570821">had</a> one piece of code only. Now I'm trying to optimize the code so that I spawn a lower number of threads.</p>
  
  <p>The point is that at the injection point I want to issue something like (sorry, <em>Datastax Java driver for Cassandra</em> code snippet):</p>
  
  <pre><code>ResultSetFuture rsFuture = session.executeAsync(query);
  </code></pre>
  
  <p>and inject <em>that</em> future into the chain. This would make the calling thread "free" of performing other things instead of sitting and waiting for the results. </p>
  
  <hr>
  
  <p>I don't know if I can make it more clear than this, but let's follow this example.</p>
  
  <p>I run a loop in the main thread:</p>
  
  <pre><code>for (int i = 0; i &lt; 1000; i++) {
      getFutureOfMyLongRunningTask(i);
  }
  </code></pre>
  
  <p>This loop lives on the main thread only, but each call to the function <em>enqueues</em> a new task in a thread pool <strong>P</strong>. Assume now that <strong>P</strong> is a fixed thread pool of size <strong>1</strong>. That means only one thread exists in <strong>P</strong>, and it is able to process <strong>1</strong> task only. The main loop, however, will enqueue all 1000 tasks. The main loop then will need to wait for all tasks to finish.</p>
  
  <p>Now suppose that the <strong>1st</strong> task out of <strong>1000</strong> needs to perform a long DB query. We have now two choices:</p>
  
  <ol>
  <li><p>The query is executed <strong>sync</strong> <em>inside</em> the processing thread (belonging to the thread pool <strong>P</strong>). That means I simply issue the query inside the <code>if (!some condition satisfied)</code> block and wait for the results. This effectively <em>blocks</em> the tasks processing because the thread pool <strong>P</strong> have no <em>free</em> threads. The only one is <em>busy blocked</em> on IO.</p></li>
  <li><p>The query is executed <strong>async</strong> <em>inside</em> the processing thread (belonging to the thread pool <strong>P</strong>).That means I issue the query inside the <code>if (!some condition satisfied)</code> block and get immediately back a future that I will listen to (probably the DB driver will spawn another thread and block <em>that</em> thread waiting for the results). However, the thread belonging to <strong>P</strong> now is <em>free</em> to process <em>at least</em> another task. </p></li>
  </ol>
  
  <p>In my opinion, option <strong>2</strong> is better than option <strong>1</strong>, and the same reasoning can be applied with thread pools of size > <strong>1</strong> or dynamic size. </p>
  
  <p>All I want is keep the thread pool as free as possible to spawn the lowest number of threads in order to avoid wasting resources.</p>
  
  <p>Hope that makes sense. If not, please could you explain where I'm wrong?</p>