ReentrantReadWriteLock 的文档中有一个关于锁降级的示例用法(请参阅此)。
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
,在我finally
在评论中释放块中的写锁之前A
,我是否还需要获取读锁作为评论中的代码B
并C
做?或者代码可以利用volatile
?