Documentation for java.util.concurrent.locks.ReentrantReadWriteLock
Disclaimer: I'm not very good at Java and just comparing read/writer locks between C# and Java to understand this topic better & decisions behind both implementations.
There is JavaDoc about ReentrantReadWriteLock. It states the following about upgrade/downgrade for locks:
- 开发者_如何学JAVALock downgrading ... However, upgrading from a read lock to the write lock is not possible.
It also has the following example that shows manual upgrade from read lock to write lock:
// Here is a code sketch showing how to exploit reentrancy
// to perform lock downgrading after updating a cache
void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// upgrade lock manually
#1: rwl.readLock().unlock(); // must unlock first to obtain writelock
#2: rwl.writeLock().lock();
if (!cacheValid) { // recheck
...
}
...
}
use(data);
rwl.readLock().unlock();
Does it mean that actually the sample from above may not behave correctly in some cases - I mean there is no lock between lines #1 & #2 and underlying structure is exposed to changes from other threads. So it can not be considered as the correct way to upgrade the lock or do I miss something here?
Yes, you are right. But this code handles the situation by calling if (!cacheValid) { // recheck
again after it acquired the write lock.
精彩评论