To Jon Park: I had difficulty understanding the use of the so-called "cookie" value returned by the lock method and used by the unlock method to release the record.
Like you I thought, I need not darn stupid cookie, I just need to know if the record is lock or not.
At the end, I used the cookie to identify the thread that locked the record and I changed a bit my implementation of the lock method to take into account the possibility that the current thread already owns the record lock. This is the only use I could find for the cookie value.
Somewhat like this:
In other words, if it is locked with the same cookie, then I do not await and let the thread proceed with the operation.
Now, this is only useful if there is a possibility to have nested record locks, which in my design is not. Because as you well mentioned, I get the lock, do the work and release it. I never get a nested lock anywhere.
To mohamed sulibi You said you follow the following approach:
lock()->read()->validate()->update()->unlock() sequence.
I think you might like to reconsider the performance issue. The idea of a lock is to retain a resource as minimum as possible. In your approach you retain a lock while reading and validated data. This could mean a lot of time of this resource being retained. That is why the approach of lock, update, and release is so common.
To John Mattman You said:
If a record is locked for a specific amount of time(may be more that one minute), then the thread releases the lock on that record. Is this ok?.
So, you are automatically releasing a record? I do not know if that is the best approach. I had use another approach in the past, but a bit different. If after certain amount of time, if a thread cannot obtain the lock, then it fails and throws RecordNotFoundException. Somewhat like this:
But in this case I do not release the lock in question (which is hold by another thread). What I do is that I fail to obtain the record lock.
But what you are saying is a bit more difficult to implement. It implies that I need some sort of timer that determines when a thread got the record lock and after certain amount of time, if such thread has not released the lock, then you release it automatically. Although it sounds very nice, I think I would not try such complicated idea.
The only reason I can foresee for a record lock to be hold indefinitely is if a thread that requested the lock dies before releasing it. I think this could be a corner case. Perhaps pursuing a simpler design could be a better idea. But hey, I have not finished my assignment. I am just saying what I think...
What do you think?
I hope this helps!