ReentrantReadWriteLock的readerShouldBlock与apparentlyFirstQueuedIsExclusive 深入理解读锁的非公平实现

前言

ReentrantReadWriteLock的读锁或写锁的获取过程中,在CAS修改同步器状态之前,会使用readerShouldBlockwriterShouldBlock来根据当前公平模式和当前同步队列来得到当前线程是否可以继续尝试获得锁(CAS修改同步器状态)。

readerShouldBlockwriterShouldBlock封装掉了当前的公平模式(公平还是非公平的),无论是在独占锁的获取过程还是在共享锁的获取过程中,你会发现,公平实现与非公平实现的差异在于,公平实现会调用hasQueuedPredecessors,非公平实现则不会。

所以,XXXShouldBlockhasQueuedPredecessors之上进行了封装,公平实现下,XXXShouldBlock肯定会去调用hasQueuedPredecessors的。

JUC框架 系列文章目录

writerShouldBlock的非公平实现

我们首先看写锁的ShouldBlock的两种实现。

//非公平实现
        final boolean writerShouldBlock() {
            return false; // writers can always barge
        }
//公平实现
        final boolean writerShouldBlock() {
            return hasQueuedPredecessors();
        }

可见writerShouldBlock在非公平实现下,是直接返回false的。这是一种完全的非公平实现。

当一个线程想要获得写锁成功时,只有当前ReentrantReadWriteLock的写锁没有被其他线程持有,且ReentrantReadWriteLock的读锁没有被任意线程持有(注意这里是任意线程,包括自己线程持有读锁)。所以writerShouldBlock的非公平实现直接返回false,代表你尽管去非公平地尝试,反正想抢写锁成功,条件是很苛刻的。

readerShouldBlock的非公平实现

可见readerShouldBlock的实现并不是直接返false,而是调用apparentlyFirstQueuedIsExclusive。这不是一种完全的非公平实现,但这样做是有它的道理的。

//非公平实现
        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.
             */
            return apparentlyFirstQueuedIsExclusive();
        }
//公平实现
        final boolean readerShouldBlock() {
            return hasQueuedPredecessors();
        }

    /**
     * Returns {@code true} if the apparent first queued thread, if one
     * exists, is waiting in exclusive mode.  If this method returns
     * {@code true}, and the current thread is attempting to acquire in
     * shared mode (that is, this method is invoked from {@link
     * #tryAcquireShared}) then it is guaranteed that the current thread
     * is not the first queued thread.  Used only as a heuristic in
     * ReentrantReadWriteLock.
     */
    final boolean apparentlyFirstQueuedIsExclusive() {
        Node h, s;
        return (h = head) != null &&
            (s = h.next)  != null &&
            !s.isShared()         &&
            s.thread != null;
    }

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.

翻译过来就是,这只是一种启发式地避免写锁无限等待的做法,它在遇到同步队列的head后继为写锁节点时,会让readerShouldBlock返回true代表新来的读锁(new reader)需要阻塞等待这个head后继。但只是一定概率下能起到作用,如果同步队列的head后继是一个读锁,之后才是写锁的话,readerShouldBlock就肯定会返回false了。

new reader意思就是,线程第一次来尝试获取读锁。

写锁无限等待 indefinite writer starvation

在这里插入图片描述

首先解释一下indefinite writer starvation,上图中,写锁节点作为head后继阻塞等待中。

考虑readerShouldBlock的现有实现的话,写锁节点只需要等待线程AB释放读锁后,就可以获得到写锁了。而线程CDE作为new reader,不会去尝试获取读锁,而是将自己包装成读锁节点排在写锁节点的后面。这个具体的流程,请查看ReentrantReadWriteLock源码解析读锁的获取章节内容里面对fullTryAcquireShared函数的讲解,我们只需要知道readerShouldBlock返回了true,代表读锁获取应该阻塞,如果这个读锁是个new reader。

//非公平实现
        final boolean readerShouldBlock() {
            return false;
        }

但考虑readerShouldBlock如上代码这样实现的话,线程CDE即使作为new reader,因为读读不互斥,所以也会去获取到读锁。这下好了,写锁节点需要等待线程ABCDE释放读锁后,才可以获得到写锁了。

heuristic启发式地防止new reader

在这里插入图片描述
但尽管readerShouldBlock是这样的非公平实现,也无法防止上图第二种情况的new reader的获取读锁动作,所以说这只是一定概率下防止new reader获取读锁,但有概率的防止总比啥都不做强。

总结

  • readerShouldBlock的非公平实现,并不是完全的非公平实现(即直接返回false)。
  • readerShouldBlock的不完全的非公平实现,是为了防止写锁无限等待。
  • readerShouldBlock在一定概率下,防止了new reader的读锁获取动作,转而让new reader去sync queue中排队。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章