确定的答案总是在代码中,所以让我们看看那里。
这里是构造函数(注意:默认构造函数使用fair 设置false 调用这个)
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
因此,唯一的区别是sync 属性是包含FairSync 实例还是NonfairSync 实例。这些实现有何不同?
这是来自FairSync 类的writerShouldBlock 方法的代码:
final boolean writerShouldBlock() {
return hasQueuedPredecessors();
}
这意味着“如果有一行”,那么作者会阻塞并进入该行(队列)。然而,这与NonfairSync 类的实现形成鲜明对比,后者是:
final boolean writerShouldBlock() {
return false;
}
这明确显示了non fair mode 的作者如何获得高于读者的优先权。
关于作家饥饿的最后评论。在non fair mode 中,这是在伴随方法的实现中实现的:readerShouldBlock。 NonfairSync 类中的代码中的 cmets 声明:
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.
*/