【发布时间】:2018-01-20 16:25:44
【问题描述】:
ReentrantReadWriteLock 的文档中有一个关于锁降级的示例用法(请参阅this)。
class CachedData {
final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
Object data;
volatile boolean cacheValid;
void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// Must release read lock before acquiring write lock
rwl.readLock().unlock();
rwl.writeLock().lock();
try {
// 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
rwl.readLock().lock();//B
} finally {//A
rwl.writeLock().unlock(); // Unlock write, still hold read
}
}
try {
use(data);
} finally {//C
rwl.readLock().unlock();
}
}
}
如果我将Object data更改为volatile Object data,是否还需要将写锁降级为读锁?
更新
我的意思是,如果我将volatile 添加到data,在我在评论A 处释放finally 块中的写锁之前,我是否仍需要获取读锁作为comment@987654329 处的代码@andC 做吗?或者代码可以利用volatile?
【问题讨论】:
标签: java reentrantreadwritelock