From the javadoc of the ReentrantReadWriteLock class :
void processCachedData() { rwl.readLock().lock(); if (!cacheValid) { // Must release read lock before acquiring write lock 5: rwl.readLock().unlock(); 6: rwl.writeLock().lock(); // Recheck state because another thread might have acquired // write lock and changed state before we did. if (!cacheValid) { data = ... cacheValid = true; } // Downgrade by acquiring read lock before releasing write lock 14: rwl.readLock().lock(); 15: rwl.writeLock().unlock(); // Unlock write, still hold read } use(data); rwl.readLock().unlock(); }
Why should we unlock the read lock before getting the write lock, as the comment says? If the current thread holds a read lock, then it should be allowed to set a write lock when other threads are no longer reading, regardless of whether the current thread holds a read lock. This behavior I would expect.
I expect that updating the lock on lines 5 and 6 and lowering the lock on lines 14 and 15 will be done inside the ReentrantReadWriteLock class. Why is this impossible?
In other words, I would expect the code to work like this:
void processCachedData() { rwl.readLock().lock(); if (!cacheValid) {
It looks a lot better and safer to block, right?
Can someone explain the reason for this strange implementation? Thank you
source share