aspose file tools*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes B&S: locking in try/finally block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "B&S: locking in try/finally block" Watch "B&S: locking in try/finally block" New topic
Author

B&S: locking in try/finally block

Joshua Fix
Ranch Hand

Joined: Sep 18, 2007
Posts: 57
Here is some pseudo code for how I have my "book" method:

Here is my problem. I would like to throw a runtime exception in the lock method if an InterruptedException is thrown. If this happens, the record is never locked. In my unlock method, I immediately perform two checks: 1 to see if the recNo is locked and 1 to see if the current thread is the owner of the lock on the recNo. If not, I throw a RecordNotFoundException.

I don't expect an InterruptedException to ever occur, but if it does, it will basically get destroyed by the RecordNotFoundException. The client then gets notified that it's trying to unbook a method that doesn't exist/it doesn't own, which isn't what I really want to report.

The VERY last line of my lock method is putting the recNo in my HashMap. So I think it's safe to say that if the method returns without throwing an exception, it was successful. So is it OK to have my the code to book ordered like this:

This way, any exception thrown in the lock method continues to bubble up and I am sure that the unbook method is only called after a successful lock?


SCJP 5.0
Joshua Fix
Ranch Hand

Joined: Sep 18, 2007
Posts: 57
In case anybody is interested.... I couldn't bring myself to leave the lock method outside of the try block, so here's what I ended up doing:

 
jQuery in Action, 2nd edition
 
subject: B&S: locking in try/finally block