从ReentrantReadWriteLock 类 javadoc:
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();
}
为什么我们必须在获得评论中写的写锁之前释放读锁?如果当前线程持有读锁,那么无论当前线程是否也持有读锁,都应该允许在其他线程不再读取时获取写锁。这是我所期望的行为。
我希望第 5 行和第 6 行的锁升级和第 14 行和第 15 行的锁降级将在 ReentrantReadWriteLock 类内部完成。为什么这是不可能的?
换句话说,我希望代码能像这样正常工作:
void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// The readlock is upgraded to writeLock when other threads
// release their readlocks.
rwl.writeLock().lock();
// no need to recheck: other threads can't have acquired
// the write lock since this thread still holds also the readLock!!!
if (!cacheValid) {
data = ...
cacheValid = true;
}
// Downgrade by acquiring read lock before releasing write lock
rwl.writeLock().unlock(); // Unlock write, still hold read
}
use(data);
rwl.readLock().unlock();
}
这看起来是一种更好、更安全的处理锁定方式,不是吗?
有人可以解释这种奇怪实现的原因吗?谢谢。