Java Reference
In-Depth Information
A
Semaphore
manages a set of virtual
permits
; the initial number of permits is passed to
the
Semaphore
constructor. Activities can acquire permits (as long as some remain) and re-
lease permits when they are done with them. If no permit is available,
acquire
blocks until
one is (or until interrupted or the operation times out). The
release
method returns a per-
a
Semaphore
with an initial count of one. A binary semaphore can be used as a
mutex
with
nonreentrant locking semantics; whoever holds the sole permit holds the mutex.
Semaphores are useful for implementing resource pools such as database connection pools.
While it is easy to construct a fixed-sized pool that fails if you request a resource from an
empty pool, what you really want is to
block
if the pool is empty and unblock when it be-
comes nonempty again. If you initialize a
Semaphore
to the pool size,
acquire
a permit
before trying to fetch a resource from the pool, and
release
the permit after putting a re-
source back in the pool,
acquire
blocks until the pool becomes nonempty. This technique
is used in the bounded buffer class in
Chapter 12
. (An easier way to construct a blocking ob-
ject pool would be to use a
BlockingQueue
to hold the pooled resources.)
Similarly, you can use a
Semaphore
to turn any collection into a blocking bounded collec-
desired maximum size of the collection. The
add
operation acquires a permit before adding
the item into the underlying collection. If the underlying
add
operation does not actually add
anything, it releases the permit immediately. Similarly, a successful
remove
operation re-
leases a permit, enabling more elements to be added. The underlying
Set
implementation
knows nothing about the bound; this is handled by
BoundedHashSet
.
5.5.4. Barriers
We have seen how latches can facilitate starting a group of related activities or waiting for a
group of related activities to complete. Latches are single-use objects; once a latch enters the
terminal state, it cannot be reset.
Barriers
are similar to latches in that they block a group of threads until some event has oc-
curred [CPJ 4.4.3]. The key difference is that with a barrier, all the threads must come togeth-
er at a barrier point
at the same time
in order to proceed. Latches are for waiting for
events
;
barriers are for waiting for
other threads
. A barrier implements the protocol some families
use to rendezvous during a day at the mall: “Everyone meet at McDonald's at 6:00; once
you get there, stay there until everyone shows up, and then we'll figure out what we're doing
next.”