Submitting Tasks and Handling Task Results

Tasks executed by executor services are represented by implementations of either the Runnable or the Callable<V> functional interface. The following selected methods of the ExecutorService interface can be used for submitting tasks to an executor service:

Click here to view code image

Future<?> submit(Runnable task)
<V> Future<V> submit(Runnable task, V result)
<V> Future<V> submit(Callable<V> task)

All three methods submit a task for execution to the executor service. The first two methods submit a Runnable task, but the last one submits a value-returning Callable<V> task.

All three methods return a Future<V> object that represents the task. On successful execution of the task, the isDone() method of the Future<V> object will return true. The value returned in the Future<V> object can be obtained by calling the get() method on the Future<V> object. The Future object will contain the value null, or the specified result in the call, or the result of executing the value-returning Callable<V> task, respectively, for the three methods. See Example 23.2, p. 1438.

Click here to view code image

<V> List<Future<V>> invokeAll(Collection<? extends Callable<V>> tasks)
                              throws InterruptedException
<V> List<Future<V>> invokeAll(Collection<? extends Callable<V>> tasks,
                              long timeout, TimeUnit unit)
                              throws InterruptedException

Executes the given tasks and returns a list of Future<V> holding their status and results when all complete, or if the timeout expires first as in the second method. The isDone() method on each Future<V> object in the returned list of Future<V> instances will return true.

Upon return from the second method, any uncompleted tasks are cancelled through interruption. A completed task is one that has terminated either normally or by throwing an exception. The order of the Future<V> instances returned is the same as the Callable<V> tasks in the collection passed as a parameter to the methods. See Example 23.2, p. 1438.

Click here to view code image

<V> V invokeAny(Collection<? extends Callable<V>> tasks)
                throws InterruptedException, ExecutionException
<V> V invokeAny(Collection<? extends Callable<V>> tasks,
                long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException,
                       TimeoutException

Executes the given tasks, returning the result of the first one that has completed successfully without throwing an exception, if any do succeed—or before the given timeout elapses in the case of the second method. Upon return, any uncompleted tasks are cancelled. See Example 23.2, p. 1438.