Java Reference
In-Depth Information
catch(InterruptedException e) {
e.printStackTrace();
}
exec.shutdown();
}
}
Execution exception has occurred: java.lang.RuntimeException: Throwing exception from task execution...
Execution exception cause is: Throwing exception from task execution...
Executor's Completion Service
In the previous sections, I discussed how to fetch the result of a task execution using a Future object. To fetch
the result of a submitted task, you must keep the reference of the Future object returned from the executor, as
demonstrated in Listing 6-50. However, if you have a number of tasks that you have submitted to an executor and
you want to know their results as they become available, you need to use the completion service of the executor. It
is represented by an instance of the CompletionService interface. It combines an executor and a blocking queue
to hold the completed tasks references. The ExecutorCompletionService class is a concrete implementation of the
CompletionService interface. Here are the steps to use it:
Create an executor object.
ExecutorService exec = Executors.newScheduledThreadPool(3);
ExecutorCompletionService class, passing the executor created in the
previous step to its constructor.
ExecutorCompletionService CompletionService = new
ExecutorCompletionService(exec);
Create an object of
The executor completion service uses a blocking queue internally to hold the completed task.
Using another constructor, you can use your own blocking queue to hold the completed tasks.
The
take() method of the completion service returns the reference of a completed task. It
blocks if no completed task is present. If you do not want to wait, in case there is no completed
task, you can use the poll() method, which returns null if there is no completed task in the
queue. Both methods remove the completed task from the queue if they find one.
Listing 6-55, Listing 6-56, and Listing 6-57 illustrate the use of the completion service. An instance of the TaskResult
class represents the result of a task. It was necessary to have a custom object like a TaskResult to represent the result
of a task because the completion service just tells you that a task is completed and you get its result. It does not tell you
which task is completed. To identify the task that was completed, you need to identify the task in the result of the task.
Your SleepingTask returns a TaskResult from its call() method by embedding the task id and the total sleeping time
for the task.
Listing 6-55. A Class to Represent the Result of a Task
// TaskResult.java
package com.jdojo.threads;
public class TaskResult {
private int taskId;
private int result;
 
Search WWH ::




Custom Search