The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
Multiple reads can occur simultaneously without affecting other threads. Therefore, access to the recordNumbers map is a perfect candidate for a ReadWriteLock.
If the position in the file was changed by another thread between lines 203 and 204, we would end up reading from the wrong location in the file.
Roel De Nijs wrote:From the ReadWriteLock interface:
The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
So that's the key point: it allows concurrent reading by multiple threads (like you already said). Keep this in mind!
Reading some bytes from the file is a 2-step operation: first you have to position the file pointer correctly (seek), then you can actually read the bytes you want (readFully). Now it's time to think back about the concurrent reading. What happens if 2 threads access that code simultaneously? Time for some brain exercise![]()
Helen Ma wrote:I am wondering locationInFile is a method local variable that each thread has its own copy, another thread cannot "mess up" each other's locationInFile variable.
Helen Ma wrote:my interpretation tells me the concurrent reading won't cause reading a wrong location. Will Th 2 read the locationInFile specified by Th 1? I don't think so because Th 2 has no idea what value of locationInFile Th 1 has.
Helen Ma wrote:If that is the right logic,
Helen Ma wrote:What may be possible is :
1. T1 will execute this : database.readFully(input) to read data at offset= 150, assume the length of the record is 75. It is possible that the file pointer stops at 200 and the scheduler makes T1 wait and let T2 run.
2 . Since T2 can also acquire the read lock, T2 execute seek (225). The file pointer points from 200 to 225. T2 finishes readFully and the file pointer points at 300. Scheduler makes T2 wait and let T1 run.
3. When T1 continues, the file pointer starts at 300 , read the rest of the data, and stops at 325.
Result: Reading the data for T1 is expected to be from 150 to 225. But the output is 325, which is wrong.
Helen Ma wrote:Another possible is:
1. T1 execute readFully(input) and finishes the reading. The file pointer moves from 150 to 225. Scheduler makes T1 waits and let T2 run.
2. T2 acquires the read lock. T2 execute seek (225). The file pointer moves from 225 to 300. Scheduler makes T2 wait and T1 run.
3. T2 releases the lock and then T1 release the lock.
Result: T1 reads from 150 to 225, which is correct. T2 reads from 225 to 300, which is correct.
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
|