据说,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();
现在我在 write 方法中:
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 block 中。
关于java - 如何使用 ReentrantReadWriteLock 等待数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13088363/