title: Calling ExecutorService.shutdownNow from CompletableFuture
body: <p>I need to cancel all scheduled but not yet running CompletableFuture tasks when one of already running task throws an exception.</p>
  
  <p>Tried following example but most of the time the main method does not exit (probably due to some type of deadlock).</p>
  
  <pre><code>public static void main(String[] args) {
      ExecutorService executionService = Executors.newFixedThreadPool(5);
  
      Set&lt; CompletableFuture&lt;?&gt; &gt; tasks = new HashSet&lt;&gt;();
  
      for (int i = 0; i &lt; 1000; i++) {
          final int id = i;
          CompletableFuture&lt;?&gt; c = CompletableFuture
  
          .runAsync( () -&gt; {
              System.out.println("Running: " + id); 
              if ( id == 400 ) throw new RuntimeException("Exception from: " + id);
          }, executionService )
  
          .whenComplete( (v, ex) -&gt; { 
              if ( ex != null ) {
                  System.out.println("Shutting down.");
                  executionService.shutdownNow();
                  System.out.println("shutdown.");
              }
          } );
  
          tasks.add(c);
      }
  
      try{ 
          CompletableFuture.allOf( tasks.stream().toArray(CompletableFuture[]::new) ).join(); 
      }catch(Exception e) { 
          System.out.println("Got async exception: " + e); 
      }finally { 
          System.out.println("DONE"); 
      }        
  }
  </code></pre>
  
  <p>Last printout is something like this:</p>
  
  <pre><code>Running: 402
  Running: 400
  Running: 408
  Running: 407
  Running: 406
  Running: 405
  Running: 411
  Shutting down.
  Running: 410
  Running: 409
  Running: 413
  Running: 412
  shutdown.
  </code></pre>
  
  <p>Tried running <code>shutdownNow</code> method on separate thread but it still, most of the time, gives the same deadlock.</p>
  
  <p>Any idea what might cause this deadlock?</p>
  
  <p>And what you think is the best way to cancel all scheduled but not yet running <code>CompletableFuture</code>s when exception is thrown?</p>
  
  <p>Was thinking of iterating over <code>tasks</code> and calling <code>cancel</code> on each <code>CompletableFuture</code>. But what I dont like about this is that throws <code>CancellationException</code> from <code>join</code>.</p>