title: Wait until any of Future<T> is done
body: <p>I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished).
  Currently they are presented as Future, so I need something like</p>
  
  <pre><code>/**
   * Blocks current thread until one of specified futures is done and returns it. 
   */
  public static &lt;T&gt; Future&lt;T&gt; waitForAny(Collection&lt;Future&lt;T&gt;&gt; futures) 
          throws AllFuturesFailedException
  </code></pre>
  
  <p>Is there anything like this? Or anything similar, not necessary for Future. Currently I loop through collection of futures, check if one is finished, then sleep for some time and check again. This looks like not the best solution, because if I sleep for long period then unwanted delay is added, if I sleep for short period then it can affect performance.</p>
  
  <p>I could try using </p>
  
  <pre><code>new CountDownLatch(1)
  </code></pre>
  
  <p>and decrease countdown when task is complete and do </p>
  
  <pre><code>countdown.await()
  </code></pre>
  
  <p>, but I found it possible only if I control Future creation. It is possible, but requires system redesign, because currently logic of tasks creation (sending Callable to ExecutorService) is separated from decision to wait for which Future. I could also override </p>
  
  <pre><code>&lt;T&gt; RunnableFuture&lt;T&gt; AbstractExecutorService.newTaskFor(Callable&lt;T&gt; callable)
  </code></pre>
  
  <p>and create custom implementation of RunnableFuture with ability to attach listener to be notified when task is finished, then attach such listener to needed tasks and use CountDownLatch, but that means I have to override newTaskFor for every ExecutorService I use - and potentially there will be implementation which do not extend AbstractExecutorService. I could also try wrapping given ExecutorService for same purpose, but then I have to decorate all methods producing Futures.</p>
  
  <p>All these solutions may work but seem very unnatural. It looks like I'm missing something simple, like </p>
  
  <pre><code>WaitHandle.WaitAny(WaitHandle[] waitHandles)
  </code></pre>
  
  <p>in c#. Are there any well known solutions for such kind of problem?</p>
  
  <p>UPDATE:</p>
  
  <p>Originally I did not have access to Future creation at all, so there were no elegant solution. After redesigning system I got access to Future creation and was able to add countDownLatch.countdown() to execution process, then I can countDownLatch.await() and everything works fine.
  Thanks for other answers, I did not know about ExecutorCompletionService and it indeed can be helpful in similar tasks, but in this particular case it could not be used because some Futures are created without any executor - actual task is sent to another server via network, completes remotely and completion notification is received.</p>