java.util.concurrent.ExecutorCompletionService Maven / Gradle / Ivy
package java.util.concurrent;
import java.util.Objects;
public class ExecutorCompletionService implements CompletionService {
private final Executor executor;
private final AbstractExecutorService aes;
private final BlockingQueue> completionQueue;
private class QueueingFuture extends FutureTask {
QueueingFuture(RunnableFuture task) {
super(task, null);
this.task = task;
}
protected void done() {
completionQueue.add(task);
}
private final Future task;
}
private RunnableFuture newTaskFor(Callable task) {
return (aes != null) ? aes.newTaskFor(task) : new FutureTask(task);
}
private RunnableFuture newTaskFor(Runnable task, V result) {
return (aes != null) ? aes.newTaskFor(task, result) : new FutureTask(task, result);
}
public ExecutorCompletionService(Executor executor) {
Objects.requireNonNull(executor);
this.executor = executor;
this.aes = (executor instanceof AbstractExecutorService) ? (AbstractExecutorService) executor : null;
this.completionQueue = new LinkedBlockingQueue>();
}
public ExecutorCompletionService(Executor executor, BlockingQueue> completionQueue) {
Objects.requireNonNull(executor);
Objects.requireNonNull(completionQueue);
this.executor = executor;
this.aes = (executor instanceof AbstractExecutorService) ? (AbstractExecutorService) executor : null;
this.completionQueue = completionQueue;
}
public Future submit(Callable task) {
Objects.requireNonNull(task);
RunnableFuture f = newTaskFor(task);
executor.execute(new QueueingFuture(f));
return f;
}
public Future submit(Runnable task, V result) {
Objects.requireNonNull(task);
RunnableFuture f = newTaskFor(task, result);
executor.execute(new QueueingFuture(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);
}
}