[concurrency-interest] Making ExecutorService return on first failure?

Outside - Karl's ACM kpauls at acm.org
Thu Mar 12 16:02:53 EDT 2009


ExecutorService can be scheduled or canceled from any thread, but that means wrapping all of your callables in wrappers tooled with the abort code.
 
Is CompletionService suitable for your needs? It too wraps all callables you submit to it inside some task management code so you won't have to.
 
// -- begin
ExecutorService exec = Executors.newFixedThreadPool(3);
ExecutorCompletionService<?> completion = new ExecutorCompletionService<?>(exec);
// submit 2 ok quick running tasks, 1 quick excepting task
// submit 1 LONG running task
 
while(false == exec.isShutdown()) {
    try {
        Future<?> f = completion.take();
    } catch (Exception e) {
        exec.shutdownNow();
    }
}
// -- end
 
That will do what you want in a procedural manner... except that it shuts down all tasks as soon as you hit an exception. So you will need to define a new executor for each batch of dependent tasks. It looks like that is acceptible.

I've started to have some doubt of the universal utility of CompletionService - feeling that it may be better in most cases to go down to implementing with blocking queues themselves instead of composing nested or inter-dependent tasks inside of the CompletionService (there's a blog post brewing in this after I explore the topic).
 
-karl



More information about the Concurrency-interest mailing list