/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain. Use, modify, and * redistribute this code in any way without acknowledgement. */ package java.util.concurrent; /** * A {@link CompletionService} that uses a supplied {@link Executor} * to execute tasks. An ExecutorCompletionService can be * useful as an add-on to solve task coordination problems. * *
* * Usage Examples. * Suppose you have a set of solvers for a certain problem, * and would like to run them concurrently, using the results of each of them * that return a non-null value. You could write this as: * *
* void solve(Executor e, Collection<Callable<Result>> solvers) * throws InterruptedException, ExecutionException { * ExecutorCompletionService<Result> ecs = new * ExecutorCompletionService<Result>(e); * for (Callable<Result> s : solvers) * ecs.submit(s); * int n = solvers.size(); * for (int i = 0; i < n; ++i) { * Result r = ecs.take().get(); * if (r != null) * use(r); * } * } ** * Suppose instead that you would like to use the first non-null result * of a set of tasks, ignoring any of those that encounter exceptions * and cancelling all of the other tasks when the first one is ready: * *
* void solve(Executor e, Collection<Callable<Result>> solvers) * throws InterruptedException { * ExecutorCompletionService<Result> ecs = * new ExecutorCompletionService<Result>(e); * int n = solvers.size(); * ArrayList<Future<Result>> futures = * new ArrayList<Future<Result>>(n); * Result result = null; * try { * for (Callable<Result> s : solvers) * futures.add(ecs.submit(s)); * for (int i = 0; i < n; ++i) { * try { * Result r = ecs.take().get(); * if (r != null) { * result = r; * break; * } * } catch(ExecutionException ignore) {} * } * } * finally { * for (Future<Result> f : futures) * f.cancel(true); * } * * if (result != null) * use(result); * } **/ public class ExecutorCompletionService