File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes B&S - Locking Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "B&S - Locking" Watch "B&S - Locking" New topic

B&S - Locking

Joshua Fix
Ranch Hand

Joined: Sep 18, 2007
Posts: 57
Are we to rely solely on our own defined record locking mechanism and provide no synchronization in the class that accesses the database file?

My code is synchronized and works fine even if I don't call my lock or unlock methods. The worst that happens is a RecordNotFoundException is thrown if the record doesn't exist or is marked as deleted. So it seems my lock and unlock methods don't provide any added value.

SCJP 5.0
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11778

Hi Joshua

I think you are asking the same question in different ways in your 2 threads, so I am going to post this reply in both. (Thanks for taking the time to rephrase your question though).

You might want to look at the JavaRanch SCJD FAQ. In particular the section on "Can't we synchronize the update() method and ignore the lock() methods?" which is also the same as the section "Why do we have lock() methods in the Data class?"

Regards, Andrew

The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
Joshua Fix
Ranch Hand

Joined: Sep 18, 2007
Posts: 57
Thanks Andrew. Your book has been an invaluable resource to me in this little adventure.

The FAQ makes perfect sense, and I realized why it was that there seemed to be no difference in my testing results if I called lock/unlock before modifying a record or not: I was using my Data class as a facade and passing in an the instance of my Data class to my LockManager as the "cookie" to identify the client, then storing the recNo and Data instance in a map. A couple of days ago I decided to make my Data class a singleton... so every client had the same instance. The portion of my lock method checks to see if the current client already owns the lock, and if so, returns.

I decided to change my cookie from an instance of the Data class to Thread.currentThread(). My tests run MUCH cleaner now, and I only get legitimate invalid record warnings when a thread is waiting for the lock on a record and the previous owner deletes the record. And based on the fact that I wasn't really doing any record locking before, I'm guessing my synchronization blocks are correct

Thanks again!
I agree. Here's the link:
subject: B&S - Locking
jQuery in Action, 3rd edition