I am so confused on this issue. My assignment DB interface something look like this:
public String read(int recNo) throws RecordNotFoundException; // Modifies the fields of a record. The new value for field n // appears in data[n]. Throws SecurityException // if the record is locked with a cookie other than lockCookie. public void update(int recNo, String data, long lockCookie) throws RecordNotFoundException, SecurityException; // Deletes a record, making the record number and associated disk // storage available for reuse. // Throws SecurityException if the record is locked with a cookie // other than lockCookie. public void delete(int recNo, long lockCookie) throws RecordNotFoundException, SecurityException;
As you see when performing lock record, a lockCookie is needed. Does that mean that if I use lockCookie to control lock, I don't need synchronized to lock the object? Advice please. I am so confused them. Am i supposed to use both of just either of them?
author and jackaroo
I am a little confused by what you are asking here, but I suspect that it is the same question that we have in the JavaRanch SCJD FAQ:
Can't we synchronize the update() method and ignore the lock() methods?
Why do we have lock() methods in the Data class?
Most of the file operations require some synchronization, as they involve accessing a single shared resource. Even worse, they often involve two operations on that single shared resource, where the two operations must behave atomically. That is, you would normally perform a seek() and then a write(), however you do not want any other thread to perform a seek() between when you performed your seek() and when you perform your write(), otherwise you will end up writing in the wrong location within the file.
(We will ignore for the moment the question of whether it is better to synchronize the entire update() method in Data class, or whether to just put the seek() and write() methods within a syncronized block.)
So having somehow synchronized the access to the file, we still have a problem of two clients believing that a record is available, and both trying to update it. That is:now client B has overwritten client A's booking
This is where the logical record locking available through the lock() and unlock() methods of the Data class come in - in the above scenario, if client A had logically locked record 5 prior to checking availability, and client B had attempted to locally lock record 5 prior to checking availability, then client B would be blocked until client A had finished - no more problem.Does that answer your question? If not, could you rephrase it?