Java Reference
In-Depth Information
licBarrier instancesareusefulinapplicationsinvolvingfixedsizedparties
of threads that must occasionally wait for each other. CyclicBarrier sup-
portsanoptional Runnable ,knownasa barrier action ,whichrunsonceper
barrierpointafterthelastthreadinthepartyarrivesbutbeforeanythreadsare
released.Thisbarrieractionisusefulforupdatingsharedstatebeforeanyofthe
parties continue.
• An exchanger lets a pair of threads exchange objects at a synchronization
point. The java.util.concurrent.Exchanger class implements this
synchronizer.Eachthreadpresentssomeobjectonentryto Exchanger 's ex-
change() method, matches with a partner thread, and receives its partner's
object on return. Exchangers may be useful in applications such as genetic
algorithms (see http://en.wikipedia.org/wiki/Genet-
ic_algorithm ) and pipeline designs.
• A phaser is a reusable synchronization barrier that is similar in functionality
to CyclicBarrier and CountDownLatch , but offers more flexibility.
For example, unlike with other barriers, the number of threads that register
to synchronize on a phaser may vary over time. The
java.util.concurrent.Phaser class implements this synchronizer.
Phaser may be used instead of a CountDownLatch to control a one-shot
action that serves a variable number of parties. It may also be used by tasks
executing in the context of the Fork/Join Framework, discussed later in this
chapter.
• A semaphore maintains a set of permits for restricting the number of threads
that can access a limited resource. The
java.util.concurrent.Semaphore class implements this synchron-
izer.Eachcalltooneof Semaphore 's acquire() methodsblocksifneces-
saryuntilapermitisavailable,andthentakesit.Eachcallto release() adds
a permit, potentially releasing a blocking acquirer. However, no actual permit
objectsareused;the Semaphore instanceonlykeepsacountofthenumberof
availablepermitsandactsaccordingly. Semaphore sareoftenusedtorestrict
the number of threads than can access some (physical or logical) resource.
Consider the CountDownLatch class. Each of its instances is initialized to a
nonzero count. A thread calls one of CountDownLatch 's await() methods to
blockuntilthecountreaches zero.Anotherthreadcalls CountDownLatch 's coun-
tDown() method to decrement the count. Once the count reaches zero, the waiting
threads are allowed to continue.
Search WWH ::




Custom Search