There is a sample usage about lock downgrading in the doc of ReentrantReadWriteLock(see 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();
}
}
}
If I change Object data
to volatile Object data
, should I still need downgrading write lock to read lock?
update
What I mean is if I add volatile
to data
,Before I release the write lock in finally
block at comment A
,should I still need acquiring the read lock as the code at commentB
andC
do? Or the code can take the advantage of volatile
?