I've read a lot of topics about the locking mechanism and just want to get your opinion on whether my strategy holds up?
1.Lock and unlock method are not synchronized - all other methods in the class are synchronized
2.Uses reentrant lock to create critical section for threads looking for record lock
3.Once
thread has reentrant lock it calls a synchronized method to check if record exists
4.Waits on a reentrant lock Condition object inside while loop if record lock held by another thread
5.When record lock is available thread calls synchronized doesRecordExist method again to verify record was not deleted
6.Creates cookie and adds to map
7.Releases reentrant lock and exits lock method
With this approach it is possible that thread A can execute one of my public synchronized methods while Thread B is inside the lock or unlock method. However because the method to check if a record exists is synchronized it means that the lock method will have to wait for any CRUD operations to complete before it can check if record exists. So no data corruption in my opinion.
To lock the database I then have a synchronized method which closes the RandomAccessFile object in my DataFileAccess class (this class does all IO operations on data file) and then set its reference to null. Because the method is synchronized it means that no other CRUD operation can occur at this point. It is possible that another running thread could enter the lock method after this and attempt to obtain a lock for a record however an
IllegalStateException will be thrown when the check is called from the lock method to see if a record exists or not. It is possible also that another thread who was waiting to enter a synchronized block to update or delete a record does so but an IllegalStateException will be thrown because the DataFileAccess reference is no longer valid.
Does this sound like a valid approach?