Java Reference
In-Depth Information
246 public boolean addDvd(DVD dvd) throws IOException {
247 return persistDvd(dvd, true);
248 }
We start the persistDVD method by seeing if the provided UPC is in our map of known
UPCs, and verifying whether we are creating or modifying the DVD record. If we are creating a
record the UPC must not be in our map. If we are modifying the DVD, then the UPC must be
in our map. In any other case we cannot proceed, so we return false to indicate that the opera-
tion failed. Since we may be potentially adding the DVD's UPC to our map of known UPCs, we
need to obtain a write lock on the recordNumbersLock .
Note Normally it is a bad idea to use return values to indicate success or failure of a call to a method—
we should be able to throw an exception if we cannot continue. An exception would provide greater detail of
what went wrong, and more importantly what the stack trace was at the time. However, the DBClient inter-
face has specified that the addDVD , modifyDVD , and removeDVD methods must return a Boolean to indicate
success or failure, so we must follow the dictates of the interface or we risk causing other programmer's
code to fail. As with the assignment you get from Sun, we have simulated an interface where the reasons for
the methods, parameters, return values, and exceptions have not been specified.
Leaving this method without releasing our write lock could be disastrous: no other thread
would ever be able to gain a read or a write lock on recordNumbersLock , effectively rendering
most of our methods inoperable. To guard against this, immediately after gaining the write
lock we enter a try … finally block, and release the lock in the finally clause at line 357.
338 private boolean persistDvd(DVD dvd, boolean create) throws IOException {
339 log.entering("DvdFileAccess", "persistDvd", dvd);
340
341 // Perform as many operations as we can outside of the synchronized
342 // block to improve concurrent operations.
343 Long offset = 0L;
344 recordNumbersLock.writeLock().lock();
345 try {
346 offset = recordNumbers.get(dvd.getUPC());
347 if (create == true && offset == null) {
348 log.info("creating record " + dvd.getUPC());
349 offset = database.length();
350 recordNumbers.put(dvd.getUPC(), offset);
351 } else if (create == false && offset != null ) {
352 log.info("updating existing record " + dvd.getUPC());
353 } else {
354 return false;
355 }
356 } finally {
357 recordNumbersLock.writeLock().unlock();
358 }
Search WWH ::




Custom Search