Java Reference
In-Depth Information
This approach is convenient for a single task execution, but it is not efficient for a large
number of tasks because you have to create a thread for each task. Starting a new thread for
each task could limit throughput and cause poor performance. Using a thread pool is an ideal
way to manage the number of tasks executing concurrently. Java provides the Executor
interface for executing tasks in a thread pool and the ExecutorService interface for man-
aging and controlling tasks. ExecutorService is a subinterface of Executor , as shown in
Figure 30.7.
«interface»
java.util.concurrent.Executor
+ execute(Runnable object): void
Executes the runnable task.
«interface»
java.util.concurrent.ExecutorService
+ shutdown(): void
Shuts down the executor, but allows the tasks in the executor
to complete. Once shut down, it cannot accept new tasks.
Shuts down the executor immediately even though there are
unfinished threads in the pool. Returns a list of unfinished tasks.
Returns true if the executor has been shut down.
Returns true if all tasks in the pool are terminated.
+ shutdownNow(): List < Runnable >
+ isShutdown(): boolean
+ isTerminated(): boolean
F IGURE 30.7
The Executor interface executes threads, and the ExecutorService subinterface manages threads.
To create an Executor object, use the static methods in the Executors class, as shown
in Figure 30.8. The newFixedThreadPool(int) method creates a fixed number of threads
in a pool. If a thread completes executing a task, it can be reused to execute another task. If
a thread terminates due to a failure prior to shutdown, a new thread will be created to replace
it if all the threads in the pool are not idle and there are tasks waiting for execution. The
newCachedThreadPool() method creates a new thread if all the threads in the pool are not
idle and there are tasks waiting for execution. A thread in a cached pool will be terminated if
it has not been used for 60 seconds. A cached pool is efficient for many short tasks.
java.util.concurrent.Executors
+newFixedThreadPool(numberOfThreads:
int): ExecutorService
Creates a thread pool with a fixed number of threads executing
concurrently. A thread may be reused to execute another task
after its current task is finished.
Creates a thread pool that creates new threads as needed, but
will reuse previously constructed threads when they are
available.
+newCachedThreadPool():
ExecutorService
F IGURE 30.8
The Executors class provides static methods for creating Executor objects.
Listing 30.3 shows how to rewrite Listing 30.1 using a thread pool.
L ISTING 30.3
ExecutorDemo.java
1 import java.util.concurrent.*;
2
3 public class ExecutorDemo {
 
 
Search WWH ::




Custom Search