Java Reference
In-Depth Information
32 dvdLock.unlock();
33 }
34 return true;
35 }
We start by getting a lock on the masterLock , which allows us to retrieve the lock for our
specific UPC at line 11 or create a new lock and add it to the map if necessary at lines 13 and
14. Without this master lock, another thread could be modifying the map while we are trying
to get our lock.
In JDK 1.4 we would now have a problem—we no longer want to keep the lock on
masterLock , but if we release the masterLock before we gain a lock on our particular dvdLock ,
there is the risk that some other thread could modify the dvdLock before we managed to lock
it. However, because JDK 1.4 locking works in terms of synchronized blocks, it is not possible
to lock dvdLock and then release masterLock .
Hand-over-hand locking solves this problem for us. Before releasing the lock on
masterLock we lock dvdLock in line 16. At this point we own two locks, but we release the
masterLock in line 18, bringing us back to a single lock. At no time did we own zero locks,
and the time that we owned two locks was reduced to a minimum.
When we get to line 26, each client will be waiting for the condition specific to the lock
they are after. They will no longer be woken up when any lock is released.
This relies on a LockInformation class, which is shown in Listing 5-4.
Listing 5-4. The LockInformation Class
1 class LockInformation extends ReentrantLock {
2 private DvdDatabase reserver = null;
3 private Condition notifier = newCondition();
4
5 void setReserver(DvdDatabase reserver) {
6 this.reserver = reserver;
7 }
8
9 void releaseReserver() {
10 this.reserver = null;
11 }
12
13 Condition getCondition() {
14 return notifier;
15 }
16
17 boolean isReserved() {
18 return reserver != null;
19 }
20 }
The releaseDVD method would use the Condition from the instance of the LockInformation
class for the record being unlocked to only notify threads waiting on this particular record.
If there are a large number of threads waiting for records, this could significantly reduce the
Search WWH ::




Custom Search