title: Task executor in Java that returns first ending task
body: <p>I want to implement something that would get a collection of workers (callables), run it in parallel on a threadpool and when the fastest worker returns a result gracefully shutdown (ExecutorService.shutdownNow) other workers in order not to waste any more resources. If all of the workers finish with exceptions I need to rethrow the most important one (all exceptions thrown by workers are associated with an <code>importance</code> value). Also I need to have a timeout on the whole executor that would terminate all workers if they run for too long.</p>
  
  <p>I have thought about using RxJava for that because it feels like a concise and nice solution would be possible to be achieved here. But maybe you can come up with some better tools for that (CompletableFutures, ForkJoinTasks?). Here is a code that I have written already but it's far from being a working solution (I'm not really experienced with reactive programming and thus really struggling with this):</p>
  
  <pre><code>public T run(Collection&lt;? extends Worker&lt;T&gt;&gt; workers, long timeout) {
      ExecutorService executorService = Executors.newFixedThreadPool(workers.size());
      return Observable.from(workers)
              .timeout(timeout, TimeUnit.MILLISECONDS)
              .subscribeOn(Schedulers.from(executorService))
              .map(worker -&gt; {
                  try {
                      T res = worker.call();
                      executorService.shutdownNow();
                      return res;
                  } catch (Exception e) {
                      throw Exceptions.propagate(e);
                  }
              }).doOnError(Exceptions::propagate).toBlocking().first();
  </code></pre>
  
  <p>I would be grateful for any help on this.</p>