Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

The sequencing ofput( )andget( )calls is handled by two semaphores:semProdand
semCon. Beforeput( )can produce a value, it must acquire a permit fromsemProd. After
it has set the value, it releasessemCon. Beforeget( )can consume a value, it must acquire a
permit fromsemCon. After it consumes the value, it releasessemProd. This “give and take”
mechanism ensures that each call toput( )must be followed by a call toget( ).
Notice thatsemConis initialized with no available permits. This ensures thatput( )
executes first. The ability to set the initial synchronization state is one of the more powerful
aspects of a semaphore.


CountDownLatch

Sometimes you will want a thread to wait until one or more events have occurred. To handle
such a situation, the concurrent API suppliesCountDownLatch.ACountDownLatchis
initially created with a count of the number of events that must occur before the latch is
released. Each time an event happens, the count is decremented. When the count reaches zero,
the latch opens.
CountDownLatchhas the following constructor:


CountDownLatch(intnum)

Here,numspecifies the number of events that must occur in order for the latch to open.
To wait on the latch, a thread callsawait( ), which has the forms shown here:


void await( ) throws InterruptedException
void await(longwait, TimeUnittu) throws InterruptedException

The first form waits until the count associated with the invokingCountDownLatchreaches
zero. The second form waits only for the period of time specified bywait.The units represented
bywaitare specified bytu,which is an object theTimeUnitenumeration. (TimeUnitis
described later in this chapter.)
To signal an event, call thecountDown( )method, shown next:


void countDown( )

Each call tocountDown( )decrements the count associated with the invoking object.
The following program demonstratesCountDownLatch. It creates a latch that requires
five events to occur before it opens.


// An example of CountDownLatch.


import java.util.concurrent.CountDownLatch;


class CDLDemo {
public static void main(String args[]) {
CountDownLatch cdl = new CountDownLatch(5);


System.out.println("Starting");

new MyThread(cdl);

Chapter 26: The Concurrency Utilities 795

Free download pdf