|
| |
The java.util.concurrent package supports synchronizers,
general purpose synchronization classes that facilitate coordination between
threads.
These include:
-
Semaphore:
- A semaphore is a classic concurrency control construct. It
is basically a lock with an attached counter. Similar to the
Lock
interface, it can be used to prevent access if the lock is granted. The Semaphore
class keeps track of a set of permits. Each acquire() blocks if
necessary until a permit is available, and then takes it. Each release()
adds a permit. Note that no actual permit objects are used, the Semaphore
maintains a count of the number available and acts accordingly. A semaphore
with a counter of one can serve as a mutual exclusion lock.
-
Barrier:
-
This is a synchronization aid that allows a set of threads to
all wait for each other to reach a common barrier point. The interface to the
barrier is the
CyclicBarrier class, called cyclic because it can
be re-used after the waiting threads are released. This is useful for parallel
programming.
-
CountDown Latch:
-
A latch is a condition starting out false, but once
set true remains true forever. The java.util.concurrent.CountDownLatch class
serves as a synchronization aid that allows one or more threads to wait until
a set of operations being performed in other threads completes. This
synchronization tool is similar to a barrier in the sense that it provides
methods that allow threads to wait for a condition, but the difference is that
the release condition is not the number of threads that are waiting. Instead,
the threads are released when the specified count reaches zero. The initial
count is specified in the constructor; the latch does not reset and later
attempts to lower the count will not work.
-
Exchanger:
-
Allows two threads to exchange objects at a rendezvous
point, and can be useful in pipeline designs. Each thread presents some object
on entry to the
exchange() method and receives the object
presented by the other thread on return. As an example, consider the classical
consumer-producer problem (two entities share a channel); a description of the
problem and a sample solution using built-in synchronization techniques (wait()
and notify()) is discussed in the Java tutorial and can be found here.
You can learn more about Synchronizers by following this
link.
|