确定的答案总是在代码中,所以让我们看看那里。
这是构造函数(注意:默认构造函数调用这个fair
设置为false
)
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
因此,唯一的区别是sync
属性是包含一个FairSync
实例还是一个实例NonfairSync
。这些实现有何不同?
以下是该类writerShouldBlock
方法的代码FairSync
:
final boolean writerShouldBlock() {
return hasQueuedPredecessors();
}
这意味着“如果有一条线”,那么作者会阻塞并进入该线(队列)。但是,这与以下类的实现形成鲜明对比NonfairSync
:
final boolean writerShouldBlock() {
return false;
}
这明确地表明了non fair mode
作家如何获得高于读者的优先权。
关于作家饥饿的最后一条评论。在non fair mode
此实现伴随方法的实现:readerShouldBlock
. 类中代码的注释NonfairSync
指出:
final boolean readerShouldBlock() {
/* As a heuristic to avoid indefinite writer starvation,
* block if the thread that momentarily appears to be head
* of queue, if one exists, is a waiting writer. This is
* only a probabilistic effect since a new reader will not
* block if there is a waiting writer behind other enabled
* readers that have not yet drained from the queue.
*/