/* * 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. */ public class ExecutorCompletionService implements CompletionService { private final Executor executor; private final LinkedBlockingQueue> cq = new LinkedBlockingQueue>(); /** * FutureTask extension to enqueue upon completion */ private class QueueingFuture extends FutureTask { QueueingFuture(Callable c) { super(c); } QueueingFuture(Runnable t, T r) { super(t, r); } protected void done() { cq.add((Future)this); } } /** * Creates an ExecutorCompletionService using the supplied * executor for base task execution. Normally, this * executor should be dedicated for use by this service 8 @throws NullPointerException if executor is null */ public ExecutorCompletionService(Executor executor) { if (executor == null) throw new NullPointerException(); this.executor = executor; } /** * Return the {@link Executor} used for base * task execution. This may for example be used to shut * down the service. * @return the executor */ public Executor getExecutor() { return executor; } public Future submit(Callable task) { QueueingFuture f = new QueueingFuture(task); executor.execute(f); return f; } public Future submit(Runnable task, V result) { QueueingFuture f = new QueueingFuture(task, result); executor.execute(f); return f; } public Future take() throws InterruptedException { return cq.take(); } public Future poll() { return cq.poll(); } public Future poll(long timeout, TimeUnit unit) throws InterruptedException { return cq.poll(timeout, unit); } }