Java Reference
In-Depth Information
Listing 8.8. Modifying an
Executor
Created with the Standard Factories.
You can use this technique with your own executors to prevent the execution policy from be-
ing modified. If you will be exposing an
ExecutorService
to code you don't trust not to
modify it, you can wrap it with an
unconfigurableExecutorService
.
8.4. Extending ThreadPoolExecutor
ThreadPoolExecutor
was designed for extension, providing several “hooks” for sub-
classes to override—
beforeExecute
,
afterExecute
, and
terminate
—that can be
used to extend the behavior of
ThreadPoolExecutor
.
The
beforeExecute
and
afterExecute
hooks are called in the thread that executes
the task, and can be used for adding logging, timing, monitoring, or statistics gathering. The
afterExecute
hook is called whether the task completes by returning normally from
run
or by throwing an
Exception
. (If the task completes with an
Error
,
afterExecute
is
not called.) If
beforeExecute
throws a
RuntimeException
, the task is not executed
and
afterExecute
is not called.
The
terminated
hook is called when the thread pool completes the shutdown process,
after all tasks have finished and all worker threads have shut down. It can be used to release
resources allocated by the
Executor
during its lifecycle, perform notification or logging,
or finalize statistics gathering.
8.4.1. Example: Adding Statistics to a Thread Pool
ecute
,
afterExecute
, and
terminated
to add logging and statistics gathering. To
measure a task's runtime,
beforeExecute
must record the start time and store it some-
where
afterExecute
can find it. Because execution hooks are called in the thread that
executes the task, a value placed in a
ThreadLocal
by
beforeExecute
can be retrieved
by
afterExecute
.
TimingThreadPool
uses a pair of
AtomicLong
s to keep track of