/* * 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 BlockingQueue> completionQueue; /** * FutureTask extension to enqueue upon completion */ private class QueueingFuture extends FutureTask { QueueingFuture(Callable c) { super(c); } QueueingFuture(Runnable t, V r) { super(t, r); } protected void done() { completionQueue.add(this); } } /** * Creates an ExecutorCompletionService using the supplied * executor for base task execution and a * {@link LinkedBlockingQueue} as a completion queue. * @param executor the executor to use; normally * one 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; this.completionQueue = new LinkedBlockingQueue>(); } /** * Creates an ExecutorCompletionService using the supplied * executor for base task execution and the supplied queue as its * completion queue. * @param executor the executor to use; normally * one dedicated for use by this service * @param completionQueue the queue to use as the completion queue; * normally one dedicated for use by this service 8 @throws NullPointerException if executor or completionQueue are null */ public ExecutorCompletionService(Executor executor, BlockingQueue> completionQueue) { if (executor == null || completionQueue == null) throw new NullPointerException(); this.executor = executor; this.completionQueue = completionQueue; } 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 completionQueue.take(); } public Future poll() { return completionQueue.poll(); } public Future poll(long timeout, TimeUnit unit) throws InterruptedException { return completionQueue.poll(timeout, unit); } }