Java Reference
In-Depth Information
Because an Executor processes tasks asynchronously, at any given time the state of previ-
ously submitted tasks is not immediately obvious. Some may have completed, some may be
currently running, and others may be queued awaiting execution. In shutting down an applic-
ation, there is a spectrum from graceful shutdown (finish what you've started but don't accept
any new work) to abrupt shutdown (turn off the power to the machine room), and various
points in between. Since Executor s provide a service to applications, they should be able
to be shut down as well, both gracefully and abruptly, and feed back information to the ap-
plication about the status of tasks that were affected by the shutdown.
To address the issue of execution service lifecycle, the ExecutorService interface ex-
tends Executor , adding a number of methods for lifecycle management (as well as some
convenience methods for task submission). The lifecycle management methods of Execut-
orService are shown in Listing 6.7 .
Listing 6.7. Lifecycle Methods in ExecutorService .
The lifecycle implied by ExecutorService has three states— running , shutting down ,
and terminated . ExecutorService s are initially created in the running state. The shut-
down method initiates a graceful shutdown: no new tasks are accepted but previously sub-
mitted tasks are allowed to complete—including those that have not yet begun execution. The
shutdownNow method initiates an abrupt shutdown: it attempts to cancel outstanding tasks
and does not start any tasks that are queued but not begun.
Tasks submitted to an ExecutorService after it has been shut down are handled by
the rejected execution handler (see Section 8.3.3 ), which might silently discard the task or
might cause execute to throw the unchecked RejectedExecutionException . Once
all tasks have completed, the ExecutorService transitions to the terminated state. You
Search WWH ::




Custom Search