Invoking Tasks Collectively

Example 23.2 also illustrates invoking tasks collectively and handling the task results. An executor service defines the blocking methods invokeAll() and invokeAny() that allow a collection of Callable<V> tasks to be executed—thus implementing bulk task execution.

A list of Callable<Integer> tasks is defined at (8) in Example 23.2, where each task is represented by the Callable<Integer> diceRoll defined at (2). The list represents tasks for rolling three dice. This list is executed by calling the invokeAll() method of the executor service at (9). In contrast to the submit() method, the invokeAll() method blocks until all tasks have completed, and their results are returned in a list of Future<Integer> objects. The order of the Future<Integer> objects in the result list corresponds to the order of the tasks in the task list. The resulting list of Future<Integer> objects is processed in a stream at (10) to extract the result (i.e., an Integer) from each Future<Integer> object using the get() method, and the results are collected in a list of Integer that represents the results of throwing three dice.

On the other hand, the list of Callable<Integer> tasks is executed at (11) using the invokeAny() blocking method, which returns the result of the first task that completes successfully without throwing an exception. On return, any tasks not completed are cancelled. Note that the invokeAny() method does not return the result in a Future<Integer> object.

Only Callable<V> tasks can be executed in bulk, as Runnable tasks cannot be passed as a parameter to the invoke methods.

The ScheduledExecutorService Interface

A ScheduledExecutorService is an ExecutorService that schedules tasks to be executed after a given delay or to be executed periodically. Table 23.2 shows scheduled executor services provided by the factory methods of the Executors class.

The methods of the ScheduledExecutorService interface that schedule tasks return an object that implements the ScheduledFuture<V> interface. This interface extends the Future<V> interface, and thus provides methods to retrieve task results, to check execution status, or to cancel task execution.