Java Reference
In-Depth Information
•
Semaphore
A counting semaphore. Useful for many situations in
which access to a resource must be controlled. To use the re-
source a thread must acquire a (conceptual) permit, or token,
from the semaphore. If none is available then the thread blocks
until one is. When finished with the resource the thread releases
the permit back to the semaphore to allow other threads to pro-
ceed. A counting semaphore can hold an arbitrary number of per-
mits; a binary semaphore is a semaphore with only one permit.
•
CountDownLatch
A utility for blocking until a given number of events
have occurred or until certain conditions hold. The latch is created
with a given number of events to expect. Each thread that trig-
gers an event or sets a condition calls the
countDown
method which
decrements the initial count. A thread that calls the
await
method
will block until the latch has counted down to zero.
•
CyclicBarrier
A utility that forces all threads using the barrier to
wait until all those threads are ready to pass the barrier. This
is useful for multi-phase algorithms in which all threads must
complete a given phase before any threads commence the next
phase.
•
Exchanger
A simple utility that allows two threads to exchange
data. The first thread to arrive at the exchanger waits until the
other arrives, they then exchange data and proceed.
An
Executor
knows how to execute a taskwhich is represented by a
Run-
nable
objectand replaces the direct creation of new threads within an
application. Depending on the implementation used, the
Executor
may
execute the task in the current thread, submit the task to a thread pool
for later execution, or perhaps create a new thread to execute the task.
The
Executor
abstracts all the details of thread creation and manage-
ment and allows the problem of executing tasks to be separated from
the problem of generating tasks. An
ExecutorService
expands on the ba-
sic executor to provide lifecycle managementsuch as shutting down an
executor. Particular implementations of
ExecutorService
provide thread
pools (
ThreadPoolExecutor
) and permit the scheduling of tasks in the fu-
ture (
ScheduledThreadPoolExecutor
).