Thread pools
Thread pools are useful when the number of threads that are created need to be limited. Using a pool not only controls how many threads are created, but it can also eliminate the need to create and destroy threads repeatedly, an often expensive operation.
The following figure depicts a thread pool. Requests are assigned to threads in the pool. Some thread pools will create new threads if there are no unused threads available. Others will restrict the number of threads available. This may result in some requests being blocked.
We will demonstrate thread pools using the ThreadPoolExecutor
class. This class also provides methods that deliver status information regarding thread execution.
While the ThreadPoolExecutor
class possesses several constructors, the Executors
class provides an easy way of creating instances of the ThreadPoolExecutor
class. We will demonstrate two of these methods. First, we will use the newCachedThreadPool
method. The pool created by this method will reuse...