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 thejava.util.concurrentpackage and in its two
subpackages,java.util.concurrent.atomicandjava.util.concurrent.locks. A brief overview
of their contents is given here.
java.util.concurrent
java.util.concurrentdefines the core features that support alternatives to the built-in approaches
to synchronization and interthread communication. It defines the following key features:
Synchronizers
Executors
Concurrent collections
Synchronizers offer high-level ways of synchronizing the interactions between multiple
threads. The synchronizer classes defined byjava.util.concurrentare
Semaphore Implements the classic semaphore
CountDownLatch Waits until a specified number of events have occurred
CyclicBarrier Enables a group of threads to wait at a predefined execution point
Exchanger 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 theExecutor
interface, which is used to initiate a thread.ExecutorServiceextendsExecutorand provides
methods that manage execution. There are two implementations ofExecutorService:
ThreadPoolExecutorandScheduledThreadPoolExecutor.java.util.concurrentalso
defines theExecutorsutility class, which includes a number of static methods that simplify
the creation of various executors.
Related to executors are theFutureandCallableinterfaces. AFuturecontains a value
that is returned by a thread after it executes. Thus, its value becomes defined βin the future,β
when the thread terminates.Callabledefines a thread that returns a value.
java.util.concurrentdefines several concurrent collection classes, including
ConcurrentHashMap,ConcurrentLinkedQueue, andCopyOnWriteArraylist. These offer
concurrent alternatives to their related classes defined by the Collections Framework.
Finally, to better handle thread timing,java.util.concurrentdefines theTimeUnit
enumeration.
788 Part II: The Java Library