Java Reference
In-Depth Information
by an Executor has four phases: created , submitted , started , and completed . Since tasks
can take a long time to run, we also want to be able to cancel a task. In the Executor frame-
work, tasks that have been submitted but not yet started can always be cancelled, and tasks
that have started can sometimes be cancelled if they are responsive to interruption. Cancel-
ling a task that has already completed has no effect. (Cancellation is covered in greater detail
in Chapter 7 . )
Future represents the lifecycle of a task and provides methods to test whether the task has
completed or been cancelled, retrieve its result, and cancel the task. Callable and Future
are shown in Listing 6.11 . Implicit in the specification of Future is that task lifecycle can
only move forwards, not backwards—just like the ExecutorService lifecycle. Once a
task is completed, it stays in that state forever.
The behavior of get varies depending on the task state (not yet started, running, completed).
It returns immediately or throws an Exception if the task has already completed, but if
not it blocks until the task completes. If the task completes by throwing an exception, get
rethrows it wrapped in an ExecutionException ; if it was cancelled, get throws Can-
cellationException . If get throws ExecutionException , the underlying excep-
tion can be retrieved with getCause .
Listing 6.11. Callable and Future Interfaces.
Search WWH ::




Custom Search