APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.util.concurrent

public Class ExecutorCompletionService<V>

extends Object
implements CompletionService<V>
Class Inheritance
All Implemented Interfaces
java.util.concurrent.CompletionService
Type Parameters
<V>
the type of values the tasks of this service produce and consume
Imports
java.util.Objects

A CompletionService that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.

Usage Examples. Suppose you have a set of solvers for a certain problem, each returning a value of some type Result, and would like to run them concurrently, processing the results of each of them that return a non-null value, in some method use(Result r). You could write this as:

 void solve(Executor e,
           Collection<Callable<Result>> solvers)
    throws InterruptedException, ExecutionException {
  CompletionService<Result> cs
      = new ExecutorCompletionService<>(e);
  solvers.forEach(cs::submit);
  for (int i = solvers.size(); i > 0; i--) {
    Result r = cs.take().get();
    if (r != null)
      use(r);
  }
}
Suppose instead that you would like to use the first non-null result of the set of tasks, ignoring any that encounter exceptions, and cancelling all other tasks when the first one is ready:
 void solve(Executor e,
           Collection<Callable<Result>> solvers)
    throws InterruptedException {
  CompletionService<Result> cs
      = new ExecutorCompletionService<>(e);
  int n = solvers.size();
  List<Future<Result>> futures = new ArrayList<>(n);
  Result result = null;
  try {
    solvers.forEach(solver -> futures.add(cs.submit(solver)));
    for (int i = n; i > 0; i--) {
      try {
        Result r = cs.take().get();
        if (r != null) {
          result = r;
          break;
        }
      } catch (ExecutionException ignore) {}
    }
  } finally {
    futures.forEach(future -> future.cancel(true));
  }

  if (result != null)
    use(result);
}
Since
1.5

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
ExecutorCompletionService.QueueingFuture<V>

FutureTask extension to enqueue upon completion.

Field Summary

Modifier and TypeField and Description
private final AbstractExecutorService
private final BlockingQueue<Future<V>>
private final Executor

Constructor Summary

AccessConstructor and Description
public
ExecutorCompletionService(Executor
the executor to use
executor
)

Creates an ExecutorCompletionService using the supplied executor for base task execution and a LinkedBlockingQueue as a completion queue.

public
ExecutorCompletionService(Executor
the executor to use
executor
,
BlockingQueue<Future<V>>
the queue to use as the completion queue normally one dedicated for use by this service. This queue is treated as unbounded -- failed attempted Queue.add operations for completed tasks cause them not to be retrievable.
completionQueue
)

Creates an ExecutorCompletionService using the supplied executor for base task execution and the supplied queue as its completion queue.

Method Summary

Modifier and TypeMethod and Description
private RunnableFuture<V>
private RunnableFuture<V>
newTaskFor(Runnable task, V result)

public Future<V>
poll()

Implements java.util.concurrent.CompletionService.poll.

Retrieves and removes the Future representing the next completed task, or null if none are present.

public Future<V>
poll(long timeout, TimeUnit unit)

Implements java.util.concurrent.CompletionService.poll.

Retrieves and removes the Future representing the next completed task, waiting if necessary up to the specified wait time if none are yet present.

public Future<V>
submit(Callable<V> task)

Implements java.util.concurrent.CompletionService.submit.

Submits a value-returning task for execution and returns a Future representing the pending results of the task.

public Future<V>
submit(Runnable task, V result)

Implements java.util.concurrent.CompletionService.submit.

Submits a Runnable task for execution and returns a Future representing that task.

public Future<V>
take()

Implements java.util.concurrent.CompletionService.take.

Retrieves and removes the Future representing the next completed task, waiting if none are yet present.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

aesback to summary
private final AbstractExecutorService aes
completionQueueback to summary
private final BlockingQueue<Future<V>> completionQueue
executorback to summary
private final Executor executor

Constructor Detail

ExecutorCompletionServiceback to summary
public ExecutorCompletionService(Executor executor)

Creates an ExecutorCompletionService using the supplied executor for base task execution and a LinkedBlockingQueue as a completion queue.

Parameters
executor:Executor

the executor to use

Exceptions
NullPointerException:
if executor is null
ExecutorCompletionServiceback to summary
public ExecutorCompletionService(Executor executor, BlockingQueue<Future<V>> completionQueue)

Creates an ExecutorCompletionService using the supplied executor for base task execution and the supplied queue as its completion queue.

Parameters
executor:Executor

the executor to use

completionQueue:BlockingQueue<Future<V>>

the queue to use as the completion queue normally one dedicated for use by this service. This queue is treated as unbounded -- failed attempted Queue.add operations for completed tasks cause them not to be retrievable.

Exceptions
NullPointerException:
if executor or completionQueue are null

Method Detail

newTaskForback to summary
private RunnableFuture<V> newTaskFor(Callable<V> task)
newTaskForback to summary
private RunnableFuture<V> newTaskFor(Runnable task, V result)
pollback to summary
public Future<V> poll()

Implements java.util.concurrent.CompletionService.poll.

Doc from java.util.concurrent.CompletionService.poll.

Retrieves and removes the Future representing the next completed task, or null if none are present.

pollback to summary
public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException

Implements java.util.concurrent.CompletionService.poll.

Doc from java.util.concurrent.CompletionService.poll.

Retrieves and removes the Future representing the next completed task, waiting if necessary up to the specified wait time if none are yet present.

Exceptions
InterruptedException:
if interrupted while waiting
submitback to summary
public Future<V> submit(Callable<V> task)

Implements java.util.concurrent.CompletionService.submit.

Doc from java.util.concurrent.CompletionService.submit.

Submits a value-returning task for execution and returns a Future representing the pending results of the task. Upon completion, this task may be taken or polled.

Exceptions
RejectedExecutionException:
if the task cannot be scheduled for execution
NullPointerException:
if the task is null
submitback to summary
public Future<V> submit(Runnable task, V result)

Implements java.util.concurrent.CompletionService.submit.

Doc from java.util.concurrent.CompletionService.submit.

Submits a Runnable task for execution and returns a Future representing that task. Upon completion, this task may be taken or polled.

Exceptions
RejectedExecutionException:
if the task cannot be scheduled for execution
NullPointerException:
if the task is null
takeback to summary
public Future<V> take() throws InterruptedException

Implements java.util.concurrent.CompletionService.take.

Doc from java.util.concurrent.CompletionService.take.

Retrieves and removes the Future representing the next completed task, waiting if none are yet present.

Exceptions
InterruptedException:
if interrupted while waiting
java.util.concurrent back to summary

private Class ExecutorCompletionService.QueueingFuture<V>

extends FutureTask<Void>
Class Inheritance

FutureTask extension to enqueue upon completion.

Field Summary

Modifier and TypeField and Description
private final BlockingQueue<Future<V>>
private final Future<V>

Constructor Summary

AccessConstructor and Description
pack-priv
QueueingFuture(RunnableFuture<V> task, BlockingQueue<Future<V>> completionQueue)

Method Summary

Modifier and TypeMethod and Description
protected void
done()

Overrides java.util.concurrent.FutureTask.done.

Protected method invoked when this task transitions to state isDone (whether normally or via cancellation).

Inherited from java.util.concurrent.FutureTask:
cancelexceptionNowgetgetisCancelledisDoneresultNowrunrunAndResetsetsetExceptionstatetoString

Field Detail

completionQueueback to summary
private final BlockingQueue<Future<V>> completionQueue
taskback to summary
private final Future<V> task

Constructor Detail

QueueingFutureback to summary
pack-priv QueueingFuture(RunnableFuture<V> task, BlockingQueue<Future<V>> completionQueue)

Method Detail

doneback to summary
protected void done()

Overrides java.util.concurrent.FutureTask.done.

Doc from java.util.concurrent.FutureTask.done.

Protected method invoked when this task transitions to state isDone (whether normally or via cancellation). The default implementation does nothing. Subclasses may override this method to invoke completion callbacks or perform bookkeeping. Note that you can query status inside the implementation of this method to determine whether this task has been cancelled.