I am getting confused with synchronization in the database file.
My db interface has the following methods:
read, update, delete, find, lock, unlock and create.
I have a Data object that implements this db interface. Data has a singleton LockHandler to deal with all the locking and unlocking of records and a singleton FileHandler to deal with all the reads/writes to the database.
I have a Hashtable hDatabase to hold the record data and record id for all live records (not deleted records) and a RandomAccessFile raf to read/write to the actual database file. - Not sure whether to keep this open at all times or to open + close before and after a read or write to the database.
So, for db.read and db.find, a client needs a lock on hDatabase to be able to read/search for a record. - IS THIS NECESSARY??
For update, delete and create a client needs a lock on the raf to read/write to the database.
However, at each write to the database, hDatabase needs to be refreshed with the data from the database so that any clients are then reading the new information. Do I lock on hDatabase only or raf or both(not good)??
Going round in circles with this one at the moment.
hmm first thing is that you need to synchronize your CRUD methods so that you do not land up having corrupt records. At a time only one CRUD operation happens on the data file
secondly on read and find you do not need to lock the record provided the above is true. Means if you have synchronized the CRUD access to the datafile
thirdly if you are using a hashmap to store all the data then you need to synchronize only the HashMap (you can use the utilities in Collections class)
also you will have to update the hashmap with the latest data in case of update or create. So you will have to take care that you do not end up having old data in the hashmap that is being used by other threads to read. Note that this is best done in the thread that is doing the update or the create as it will have the lock to it