java - 如何使用 ReentrantReadWriteLock 等待数据?

标签 java concurrency java.util.concurrent reentrantreadwritelock

据说,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/

相关文章:

java 信号量习语

java - 排除在 Hibernate 对象中加载特定属性

java - OpenCV 安卓工作室

java - 限制对数据库操作的并发 Web 服务调用

Java同步块(synchronized block)使用方法调用获取同步对象

java - Spring - 让 TaskExecutor 和 TaskScheduler 由同一线程池支持

java - ScheduledThreadPoolExecutor 具有同时调度的多个 Runnables,如何操作?

java - 无法运行 WordCount-Compiler 问题的 java 示例

java - 线程间的并发问题

java - 如何异步设置值并在稍后阶段获取它