This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

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

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:

Have you checked out Aspose?
subject: B&S: locking in try/finally block
It's not a secret anymore!