Java Reference
In-Depth Information
We have decided to allow any UPC to be reserved, even if no such record exists. This
ensures that a DVD can also be reserved when we are first adding it to the system. The alterna-
tive would be to have the
reserveDVD
method start by verifying that the record does exist,
throwing some exception if the record does not exist. If we had any delete methods, we would
also have to verify that the record existed after we acquired the lock. However, if we did this,
we would also have to change the logic of the
addDVD
method, and possibly the
updateDVD
method (remember, they both defer to the same private
persistDVD
method, which might also
have to be updated).
Our
reserveDVD
method acquires a mutual exclusion lock, and then goes into a while
loop, waiting until we either time out or acquire the lock.
Our
DBClient
interface specifies that we must return false if we were unable to lock the
record within 5 seconds. Under JDK 1.4 there was no guaranteed way of determining whether
a call to
wait(timeout)
had timed out or whether notification had been received. JDK 5 has a
new
Condition.await
method, which will return a Boolean
true
if we were notified by the
unlock method that we can continue processing, and
false
if we timed out.
If we have acquired the lock, we add a record to the map of lock owners, indicating that
we own the lock.
Finally, we release the mutual exclusion lock.
The Logical Release Method
The
releaseDVD
method is the counterpoint to the
reserveDVD
method shown earlier, and the
code is very similar.
void releaseDvd(String upc, DvdDatabase renter) {
log.entering("ReservationsManager", "releaseDvd",
new Object[]{upc, renter});
lock.lock();
if (reservations.get(upc) == renter) {
reservations.remove(upc);
log.fine(renter + " released lock for " + upc);
lockReleased.signal();
} else {
log.warning(renter + " cant release lock for " + upc + ": not owner");
}
lock.unlock();
log.exiting("ReservationsManager", "releaseDvd");
}
First, we ensure we have a lock on the mutual exclusion
Lock
; then if it is the owner of the
reservation who is releasing it, we remove our lock indication from the map. Then we signal
any waiting threads that they can try to acquire locks. If the wrong
renter
instance is passed to
this method, a warning message is logged. Finally, we release our mutual exclusion
Lock
.