10.8 Summary
In this chapter, we began exploration of executors: utilities that
process Runnable objects while hiding threading
details from the developer. Executors are very useful because they
allow programs to be written as a series of tasks; programmers can
focus on the logic of their program without getting bogged down in
details about how threads are created or used.
The thread pool executor is one of two key executors in Java. In
addition to the programming benefits common to all executors, thread
pools can also benefit programs that have lots of simultaneous tasks
to execute. Using a thread pool throttles the number of threads. This
reduces competition for the CPU and allows CPU-intensive programs to
complete individual tasks more quickly.
The combination of individual tasks and a lack of CPU resources is
key to when to use a thread pool. Thread pools are often considered
important because reusing threads is more efficient than creating
threads, but that turns out to be a red herring. From a performance
perspective, you'll see a benefit from thread pools
because when there is less competition for the CPU (because of fewer
threads), the average time to complete an individual task is less
than otherwise.
The key to effectively using Java's thread pool
implementation is to select an appropriate size and queueing model
for the pool. Selecting a queuing model is a factor of how you want
to handle many requests: an unbounded queue allows the requests to
accumulate while other models possibly result in rejected tasks that
must be handled by the program. A little bit of work is required to
get the most out of a thread pool. But the rewards梑oth in
terms of the simplification of program logic and in terms of
potential throughput梞ake thread pools very useful.
10.8.1 Example Classes
Here are the class names and Ant targets for the examples in this
chapter:
|
Description
|
Main Java class
|
Ant target
|
|---|
|
Fibonacci Calculator with Thread Pool
|
javathreads.examples.ch10.example1.ThreadPoolTest nRequests
NumberToCalculate ThreadPoolSize
|
ch10-ex1
| |
Fibonacci Calculator using SingleThreadAccess
|
javathreads.examples.ch10.example2.SingleThreadTest
nRequests NumberToCalculate
|
ch10-ex2
|
The properties for the Ant tasks are:
<property name="nThreads" value="10"/>
<property name="FibCalcValue" value="20"/>
<property name="ThreadPoolSize" value="5"/>
|