Java Reference
In-Depth Information
Using a factory works for both a sockets-based solution (although it is generally overkill)
and for an RMI solution. Since we are presenting both solutions in this topic, we have decided
to use a factory, and we will describe it in Chapter 6.
Creating Our Logical Reserve Methods
To create the reserveDVD and releaseDVD methods needed for logical locking, we need some
class variables. For a start, we need to track the owners of the locks; a Map containing the UPC
number and the owner is ideal. We also need a common Lock object to ensure that different
threads do not try to lock the record simultaneously. Finally, we need a condition that threads
can monitor to determine when they can attempt to acquire a lock again. These three vari-
ables are as follows:
private static Map<String, DvdDatabase> reservations
= new HashMap<String, DvdDatabase>();
private static Lock lock = new ReentrantLock();
private static Condition lockReleased = lock.newCondition();
Listing 5-2 contains the reserveDVD method.
Listing 5-2. The reserveDVD Method
boolean reserveDVD(String upc, DvdDatabase renter)
throws InterruptedException {
log.entering("ReservationsManager", "reserveDvd",
new Object[]{upc, renter});
lock.lock();
try {
long endTimeMSec = System.currentTimeMillis() + 5000;
while (reservations.containsKey(upc)) {
long timeLeftMSec = endTimeMSec - System.currentTimeMillis();
if (!lockReleased.await(timeLeftMSec, TimeUnit.MILLISECONDS)) {
log.fine(renter + " giving up after 5 seconds: " + upc);
return false;
}
}
reservations.put(upc, renter);
log.fine(renter + " got Lock for " + upc);
log.fine("Locked record count = " + reservations.size());
log.exiting("ReservationsManager", "reserveDvd", true);
return true;
} finally {
// ensure lock is always released, even if an Exception is thrown
lock.unlock();
}
}
Search WWH ::




Custom Search