Java Reference
In-Depth Information
current thread is the owner of the lock, the acquisition count is incremented; if the current
thread is not the owner of the lock, the acquisition attempt fails.
Listing 14.15. Tryacquire Implementation From Nonfair ReentrantLock .
ReentrantLock also takes advantage of AQS's built-in support for multiple condition
variables and wait sets. Lock.newCondition returns a new instance of ConditionOb-
ject , an inner class of AQS.
14.6.2. Semaphore and CountDownLatch
Semaphore uses the AQS synchronization state to hold the count of permits currently avail-
able. The tryAcquireShared method (see Listing 14.16 ) first computes the number of
permits remaining, and if there are not enough, returns a value indicating that the acquire
failed. If sufficient permits appear to be left, it attempts to atomically reduce the permit count
using compareAndSetState . If that succeeds (meaning that the permit count had not
changed since it last looked), it returns a value indicating that the acquire succeeded. The re-
turn value also encodes whether other shared acquisition attempts might succeed, in which
case other waiting threads will also be unblocked.
The while loop terminates either when there are not enough permits or when tryAc-
quireShared can atomically update the permit count to reflect acquisition. While any giv-
en call to compareAndSetState may fail due to contention with another thread (see Sec-
Search WWH ::




Custom Search