Originally posted by Mark Waldrop:
Does the following algorithm sound good for the Lock and Unlock?
long Lock(int):
Initialization
1. During the Data base interface construction, create a Random class with an input of the current Time (in ms).
2. Initialize hash map to hold locked records
Lock attempting to be performed
0. Check and make sure that the record exists
0.5 If it does not, throw a RecordNotFoundException()
1. First check that record is not already locked (check in the hash map)
2. If the record is already locked, then perform a wait()
3. If it is not, then get the next Random long sequence and insert that with the record #, into the hash map.
4. Return the Random long sequence as the lockCookie
void unlock( int, long):
1. Make sure that the record is indeed locked and it exists
1.5 If record does not exist, throw a RecordNotFoundException()
2. If it is, then get the value associated to the key and compare it to the
lockCookie passed into this method.
3. If they match, then (remove the key, value pair from the hash map) or (set the key's value to null) (haven't figured out which one is better yet) and return
4. Else if they do not match, throw a SecurityException
Please let me know what you think or ways to tweak this.
Also, should we somehow add a time limit to the locked records, in the case that one of the client sessions went down after they locked a record. Now that client will not have the lockCookie any longer.
Thanks,
Mark Waldrop
Timeouts on locks are not the way to go, if you do you will need to change the DBAccess API to provide for the case of a lock timing out. A much better solution is to let the network code deal with this by closing the Data object associated with a client or business operation when a network failure occurs. Closing that should unlock any associated locked records. This is very easy to do in a Socket based network and a bit more complex in RMI. See
my description of the RMI solution for more details.