据说ReentrantReadWriteLock
是供一位作者和多位读者使用的。
但是,读取器应该等待,直到缓冲区中存在一些数据为止。
那么,要锁定什么?
我创建了并发对象,如下所示:
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
protected final Lock readLock = rwl.readLock();
protected final Lock writeLock = rwl.writeLock();
protected final Condition hasData = writeLock.newCondition();
现在在写方法中,我这样做:
writeLock.lock();
// writing first portion and updating variables
hasData.signalAll();
// if required then writing second portion and updating variables
hasData.signalAll();
但是如何写一个读者呢?它应该只获取
readLock
吗?但是,它如何等待信号呢?如果它还需要一个writeLock
,那么读/写锁定的最高权限在哪里?如果必需的变量仅受
writeLock
保护,如何确保它们在读取期间不会改变?问题不匹配
这是关于
ReentrantReadWriteLock
的问题。 最佳答案
ReentrantReadWriteLock确实有点令人困惑,因为readLock没有条件。
您必须在阅读器中升级到writeLock才能等待这种情况。
在作家中。
writeLock.lock(); //locks all readers and writers
// do write data
hasData.signalAll();
writeLock.unlock();
在阅读器中,您可以执行以下操作:
readLock.lock(); //blocks writers only
try{
if(!checkData()) //check if there's data, don't modify shared variables
{
readLock.unlock();
writeLock.lock(); // need to lock the writeLock to allow to use the condition.
// only one reader will get the lock, other readers will wait here
try{
while(!checkData()) // check if there' still no data
{
hasData.await(); //will unlock and re-lock after writer has signalled and unlocked.
}
readLock.lock(); // continue blocking writer
}
finally
{
writeLock.unlock(); //let other readers in
}
}
//there should be data now
readData(); // don't modify variables shared by readers.
}
finally
{
readlock.unlock(); //let writers in
}
为了完整起见,当然,每个unlock()应该放在finally块中。