Now whats with this lock cookie? Am I supposed to use it? And how do I generate a sufficient lockCookie? The only thing I can think of is that this lockCookie can be used on a synchronize block when i call on a delete/update. Am i close?
Anne Crace wrote:This is actually easier than not having one.
You are so right! My given interface does not have one
why you need lock and unlock is described perfectly in the scjdfaq
Why such a lockCookie exists? very easy: when a record is locked, you generate a cookie. only a record can be updated/deleted when that same cookie-value is provided (so you have to store them with the record number). same for unlock. so you are sure that 1 client can change the record at a time. if another client tries to update the same record (it doesn't know the actual cookie value, so it will be a guess), this client will not be able to update the record and will receive a security-exception instead
First you have to synchronize the access to your db-file to not corrupt that file. an example would be: client1 (thread 1) wants to update record 1 and client2 (thread 2) wants to update record 2.
to write a record you have something like:
now if after line 1 thread 2 gets cpu it changes the filepointer and write the bytes. then thread 1 gets the cpu and the file pointer will point to another record than record 1, resulting in updating another record or making your data file corrupt. And that's not something you want, so to ensure correct behavior you must protect/synchronize access to your data file. you can do it by synchronizing on the file, using the java concurrent classes, synchronizing the complete methods,...
Secondly you have to take care of this situation (from the scjd-faq):
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:
- Client A checks that record 5 is available
- Client B checks that record 5 is available
- Client A updates record 5 with their client number
- Client B updates record 5 with their client number
now client B has overwritten client A's booking
That's the reason why you have a lock/unlock method in the interface. if client1 locks record 5, only client1 is able to update/delete this record. After client1 unlocks the record, it's back available to other records for being updated/deleted (but they have first to acquire the lock on that record).