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

news/2024/5/20 6:37:33 标签: ReadWriteLock, JUC, 多线程, AQS

文章目录

  • 前言
  • writerShouldBlock的非公平实现
  • readerShouldBlock的非公平实现
    • 写锁无限等待 indefinite writer starvation
    • heuristic启发式地防止new reader
  • 总结

前言

在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中排队。

http://www.niftyadmin.cn/n/768192.html

相关文章

JUC框架 ReentrantReadWriteLock源码解析 JDK8

文章目录前言重要成员内部类关系构造器Sync的成员同步器状态的划分读锁计数部分写锁的获取和释放写锁的获取写锁的释放读锁的获取和释放读锁的获取读锁的释放锁降级总结前言 ReentrantReadWriteLock是我阅读了AQS源码以来最感兴趣的类,因为它不像别的JUC构件只使用…

JUC集合类 CopyOnWriteArrayList源码解析 JDK8

文章目录前言核心成员常用方法getsetaddremoveremove(int index)remove(Object o)index > lenindex < lenfindIndex代码块之后cleartoArray迭代器总结前言 CopyOnWriteArrayList 是一种写时复制的ArrayList&#xff0c;它将读操作和写操作的情形区分开来&#xff0c;并在…

JUC集合类 CopyOnWriteArraySet源码解析 JDK8

文章目录前言与CopyOnWriteArrayList不同之处addIfAbsentaddAllAbsent总结前言 类似于上一篇讲的CopyOnWriteArrayList&#xff0c;CopyOnWriteArraySet可以认为是一个写时复制的HashSet。 但CopyOnWriteArraySet的底层实现完全依赖了CopyOnWriteArrayList&#xff0c;它持有…

JUC集合类 ConcurrentSkipListMap源码解析 JDK8

文章目录前言源码注释术语节点定义构造器get 查找操作返回情况findPredecessorput 插入操作假设新建层数没有超过最大层数假设新建层数超过了最大层数返回情况remove 删除操作findNodetryReduceLevel返回情况marker存在的必要性如果marker不存在marker存在时总结前言 Concurre…

ThreadLocalRandom#getProbe #advanceProbe浅析

前言 Briefly, a thread’s “probe” value is a non-zero hash code that (probably) does not collide with other existing threads with respect to any power of two collision space. When it does collide, it is pseudo-randomly adjusted (using a Marsaglia XorShif…

JUC集合类 ConcurrentHashMap源码解析 JDK8

文章目录前言常量成员节点类构造器put 插入操作加锁情况红黑树的binCount固定为2返回情况spreadinitTablehelpTransferresizeStampsizeCtl的低16bit退出循环的条件treeifyBintryPresizeaddCount计数部分计数部分结束时扩容部分CAS失败影响扩容fullAddCountwasUncontended的作用…

JDK8 ConcurrentHashMap的Bug集锦

前言 JDK8的ConcurrentHashMap并不是完美的&#xff0c;从https://bugs.openjdk.java.net/projects/JDK/issues上也可以看到JDK的很多Bug&#xff0c;当然&#xff0c;通过给concurrency-interest发邮件也可以和Doug Lea直接对话。 最重要的是&#xff0c;知道了这些bug的存在…

JUC集合类 ConcurrentLinkedQueue源码解析 JDK8

文章目录前言概述不变式基本不变式headtail初始化队列初始化Node初始化add/offer 入队操作出队操作pollpeekfirstremove 删除操作remove的bugsize 弱一致性的方法addAll迭代器总结前言 ConcurrentLinkedQueue是一种FIFO&#xff08;first-in-first-out 先入先出&#xff09;的…