such as its synchronizers, callable threads, and executors, that are applicable to a wide variety
of situations. For these reasons, this chapter presents an overview of the concurrency utilities
and shows several examples of their use.
The Concurrent API Packages
The concurrency utilities are contained in the java.util.concurrent package and in its two
subpackages, java.util.concurrent.atomic and java.util.concurrent.locks. A brief overview
of their contents is given here.
java.util.concurrent defines the core features that support alternatives to the built-in approaches
to synchronization and interthread communication. It defines the following key features:
Synchronizers offer high-level ways of synchronizing the interactions between multiple
threads. The synchronizer classes defined by java.util.concurrent are
Implements the classic semaphore
Waits until a specified number of events have occurred
Enables a group of threads to wait at a predefined execution point
Exchanges data between two threads
Notice that each synchronizer provides a solution to a specific type of synchronization
problem. This enables each synchronizer to be optimized for its intended use. In the past,
these types of synchronization objects had to be crafted by hand. The concurrent API
standardizes them and makes them available to all Java programmers.
Executors manage thread execution. At the top of the executor hierarchy is the Executor
interface, which is used to initiate a thread. ExecutorService extends Executor and provides
methods that manage execution. There are two implementations of ExecutorService:
ThreadPoolExecutor and ScheduledThreadPoolExecutor. java.util.concurrent also
defines the Executors utility class, which includes a number of static methods that simplify
the creation of various executors.
Related to executors are the Future and Callable interfaces. A Future contains a value
that is returned by a thread after it executes. Thus, its value becomes defined "in the future,"
when the thread terminates. Callable defines a thread that returns a value.
java.util.concurrent defines several concurrent collection classes, including
ConcurrentHashMap, ConcurrentLinkedQueue, and CopyOnWriteArraylist. These offer
concurrent alternatives to their related classes defined by the Collections Framework.
Finally, to better handle thread timing, java.util.concurrent defines the TimeUnit
Search WWH :