Java Reference
In-Depth Information
newFixedThreadPool. A fixed-size thread pool creates threads as tasks are submitted, up
to the maximum pool size, and then attempts to keep the pool size constant (adding
new threads if a thread dies due to an unexpected Exception ).
newCachedThreadPool. A cached thread pool has more flexibility to reap idle threads
when the current size of the pool exceeds the demand for processing, and to add new
threads when demand increases, but places no bounds on the size of the pool.
newSingleThreadExecutor. A single-threaded executor creates a single worker thread to
process tasks, replacing it if it dies unexpectedly. Tasks are guaranteed to be processed
sequentially according to the order imposed by the task queue (FIFO, LIFO, priority
order). [4]
newScheduledThreadPool. A fixed-size thread pool that supports delayed and periodic
task execution, similar to Timer . (See Section 6.2.5 . )
The newFixedThreadPool and newCachedThreadPool factories return instances of
the general-purpose ThreadPoolExecutor , which can also be used directly to construct
more specialized executors. We discuss thread pool configuration options in depth in Chapter
8 .
The web server in TaskExecutionWebServer uses an Executor with a bounded pool
of worker threads. Submitting a task with execute adds the task to the work queue, and the
worker threads repeatedly dequeue tasks from the work queue and execute them.
Switching from a thread-per-task policy to a pool-based policy has a big effect on application
stability: the web server will no longer fail under heavy load. [5] It also degrades more grace-
fully, since it does not create thousands of threads that compete for limited CPU and memory
resources. And using an Executor opens the door to all sorts of additional opportunities for
tuning, management, monitoring, logging, error reporting, and other possibilities that would
have been far more difficult to add without a task execution framework.
6.2.4. Executor Lifecycle
We've seen how to create an Executor but not how to shut one down. An Executor im-
plementation is likely to create threads for processing tasks. But the JVM can't exit until all
the (nondaemon) threads have terminated, so failing to shut down an Executor could pre-
vent the JVM from exiting.
Search WWH ::




Custom Search