Hi guys, I'm trying to get my head around the synchronization in the
SCJD Exam with J2SE book by Monkhouse & Camerlengo. Would anyone be able to tell me if my understanding is correct here?
I'm trying to understand the persistDvd method from the DvdFileAccess class. I've copied the method below.
The DvdFileAccess class does all the access and manipulation of the physical file that represents the database. The persistDvd method writes records to the database.
Would I be correct in thinking how the persistDvd is implemented could cause problems and lead to the file being corrupted when multiple threads are involved?
Take the scenario of adding a record. Assume we have two threads that are both executing the persistDvd method. We'll call these threads Thread-1 and Thread-2. So...
1.0) Thread-1 is trying to add a record that does not exist and gets an offset of null.
2.0) Then Thread-2 is trying to add a record that does not exist and gets an offset of null
3.0) Then Thread-1 goes to add its record, at offset=database.length.
4.0) Then Thread-2 goes to add its record, at offset=database.length.
........4.1) database.length hasn't changed since Thread-1 looked at it!
........4.2) the write lock is only around getting the offset and adding the record to the cache\Map.
........4.3) so both threads could potentially have the same offset?
If this scenario is correct, then depending on which
thread gets the lock on
database first, it will have the value it wrote to the database overwritten by the thread the comes after it.