Java Reference
In-Depth Information
MyThreadFactory
in
Listing 8.6
illustrates a custom thread factory. It instantiates a new
MyAppThread
, passing a pool-specific name to the constructor so that threads from each
pool can be distinguished in thread dumps and error logs.
My-AppThread
can also be used
elsewhere in the application so that all threads can take advantage of its debugging features.
Listing 8.6. Custom Thread Factory.
lets you provide a thread name, sets a custom
UncaughtException-Handler
that
writes a message to a
Logger
, maintains statistics on how many threads have been created
and destroyed, and optionally writes a debug message to the log when a thread is created or
terminates.
If your application takes advantage of
security policies
to grant permissions to particular
codebases, you may want to use the
privilegedThreadFactory
factory method in
Executors
to construct your thread factory. It creates pool threads that have the same per-
missions,
AccessControlContext
, and
contextClassLoader
as the thread creat-
ing the
privilegedThreadFactory
. Otherwise, threads created by the thread pool in-
herit permissions from whatever client happens to be calling
execute
or
submit
at the
time a new thread is needed, which could cause confusing security-related exceptions.
8.3.5. Customizing ThreadPoolExecutor After Construction
Most of the options passed to the
ThreadPoolExecutor
constructors can also be mod-
ified after construction via setters (such as the core thread pool size, maximum thread pool
size, keep-alive time, thread factory, and rejected execution handler). If the
Executor