Java Reference
In-Depth Information
Chapter 8. Applying Thread Pools
Chapter 6 introduced the task execution framework, which simplifies management of task and
thread lifecycles and provides a simple and flexible means for decoupling task submission
from execution policy. Chapter 7 covered some of the messy details of service lifecycle that
arise from using the task execution framework in real applications. This chapter looks at ad-
vanced options for configuring and tuning thread pools, describes hazards to watch for when
using the task execution framework, and offers some more advanced examples of using Ex-
ecutor .
8.1. Implicit Couplings Between Tasks and Execution Policies
We claimed earlier that the Executor framework decouples task submission from task ex-
ecution. Like many attempts at decoupling complex processes, this was a bit of an overstate-
ment. While the Executor framework offers substantial flexibility in specifying and modi-
fying execution policies, not all tasks are compatible with all execution policies. Types of tasks
that require specific execution policies include:
Dependent tasks. The most well behaved tasks are independent : those that do not depend
on the timing, results, or side effects of other tasks. When executing independent tasks
in a thread pool, you can freely vary the pool size and configuration without affecting
anything but performance. On the other hand, when you submit tasks that depend on
other tasks to a thread pool, you implicitly create constraints on the execution policy
that must be carefully managed to avoid liveness problems (see Section 8.1.1 ).
Tasks that exploit thread confinement. Single-threaded executors make stronger promises
about concurrency than do arbitrary thread pools. They guarantee that tasks are not ex-
ecuted concurrently, which allows you to relax the thread safety of task code. Objects
can be confined to the task thread, thus enabling tasks designed to run in that thread
to access those objects without synchronization, even if those resources are not thread-
safe. This forms an implicit coupling between the task and the execution policy—the
tasks require their executor to be single-threaded. [1] In this case, if you changed the
Executor from a single-threaded one to a thread pool, thread safety could be lost.
Response-time-sensitive tasks. GUI applications are sensitive to response time: users are
annoyed at long delays between a button click and the corresponding visual feedback.
Submitting a long-running task to a single-threaded executor, or submitting several
long-running tasks to a thread pool with a small number of threads, may impair the re-
sponsiveness of the service managed by that Executor .
Search WWH ::




Custom Search