Dear friends,
I hope you all fine. I am new to this site and would like to ask some questions about locking that I am having problems with and wonder if you would be able to help me. My update() method in my Data class looks like this:
Now, io is the class which contains my random access file which I use to read and write to the database file with.
My questions are these:
1. Monkhouse says that we should use while loops inside synchronized blocks instead of if statements. Hence, I have used "while (isLocked(recNo)) {". The first question is: is this right?
2. My second question involves booking records. When the user books a record I have some code that looks like this:
... lock(); ... read(); ... update(); ... unlock(); ...
In other words I lock the record in question, read the latest version of the data from the database, update database with customer id and then unlock. Here are the issues:
a) Do I need to lock() before I read() or can I lock() after read() but before update().
b) My most serious problem is this. Since I call unlock() before I call update() when I reach the while loop in update() isLocked() returns true (as it would) which means I never progress further in the method than the while loop. What should one do in this case? Should I not call lock() and unlock() in the code that deals with the user selecting a record to book or should I not call lock() and unlock() in my update() method or is there something else that I am doing wrong? The reason I wanted to call lock() and unlock() in my calling code is because I would like to 'reserve' the record early on so that in my calling code if I get swapped out by some other
thread they don't book my record under my feet. I'd be interested in knowing what you all have done.
Warm regards,
Helen