被面试官吊打系列之JUC之 可重入读写锁ReentrantReadWriteLock 之 源码详尽分析

可重入读写锁 ReentrantReadWriteLock 其实基本上模拟了文件的读写锁操作。ReentrantReadWriteLock 和ReentrantLock 的差别还是蛮大的; 但是也有很多的相似之处; ReentrantReadWriteLock 的 writerLock 其实就是相当于ReentrantLock,但是它提供更多的细腻的控制;理解什么是读锁、写锁非常重要,虽然实际工作中区分读写锁这样的细分使用场景比较少。

ReentrantReadWriteLock 把锁进行了细化,分为了两种: 读锁和写锁。它们之间有一些限制关系:

  读  写
读   Y    N
写   N    N

其中: Y 表示共享,N表示排斥(即独占)

具体分析如下

/**
ReadWriteLock的一个实现,支持类似于ReentrantLock的语义。
这个类有以下属性:

1 获取顺序
该类不为锁访问强加读线程、写线程优先顺序。但是,它确实支持一个可选的公平策略。
2 非公平模式(默认
当构造为非公平锁(默认情况下)时,读写锁的进入顺序是不指定的,受重入限制。持续争夺的非公平锁可能会无限期推迟一个或多个读写线程,但通常会比公平锁的吞吐量更高。
3 公平模式
当构造为公平时,线程使用大约到达顺序策略争夺进入。当当前持有的锁被释放时,等待时间最长的单个写线程将被分配到写锁,或者如果有一组读线程线程的等待时间超过所有等待的写线程,则该组将被分配到读锁。
试图获取公平的读锁的线程(非重入式),如果写锁被持有,或者有一个等待的写器线程,则会被阻止。该线程将在当前最老的等待写器线程获得并释放写锁后才会获得读锁。当然,如果一个等待的写器线程放弃了等待,留下一个或多个读线程、写线程作为队列中最长的等待线程,并释放了写锁,那么这些读写器线程将被分配到读锁。

一个试图获得公平写锁的线程(非重现性)将被阻塞,除非读锁和写锁都是空闲的(这意味着没有等待线程)。(注意,非阻塞的ReentrantReadWriteLock.ReadLock.tryLock()和ReentrantReadWriteLock.WriteLock.tryLock()方法不尊重这个公平设置,如果可能的话,会立即获取锁,而不考虑等待线程的情况。)

1 可重入性
这个锁允许读线程和写线程都可以用ReentrantLock的方式重新获得读锁或写锁。在写线程所持有的所有写锁被释放之前,不允许非重入式读写器获得读写锁。
此外,写线程可以获得读锁,但反之不行。在其他应用中,当在调用或回调方法执行读锁的过程中持有写锁的时候,重入性是非常有用的。如果读取器试图获取写锁,它将永远不会成功。

2 锁的降级
重入也允许从写锁降级为读锁,方法是先获得写锁,再获得读锁,然后释放写锁。但是,从读锁升级到写锁是不可能的。
锁的获取中断
读锁和写锁都支持锁获取过程中的中断。

3 条件支持
写锁提供了一个Condition实现,这个Condition实现与ReentrantLock.newCondition为ReentrantLock提供的Condition实现在写锁方面的行为是一样的。当然,这个Condition只能和写锁一起使用。
读锁不支持Condition,并且readLock().newCondition()会抛出UnsupportedOperationException。

4 仪器化
该类支持确定锁是否被持有或被争用的方法。这些方法是为监控系统状态而设计的,而不是用于同步控制。
该类的序列化与内置锁的行为方式相同:无论序列化时锁的状态如何,反序列化后的锁都处于未锁状态。
使用示例。下面是一个代码草图,展示了如何在更新缓存后执行锁的降级(当以非嵌套方式处理多个锁时,异常处理特别棘手)。

 * <pre> {@code
 * class CachedData {
 *   Object data;
 *   volatile boolean cacheValid;
 *   final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
 *
 *   void processCachedData() {
 *     rwl.readLock().lock();
 *     if (!cacheValid) {
 *       // Must release read lock before acquiring write lock
 *       rwl.readLock().unlock();
 *       rwl.writeLock().lock();
 *       try {
 *         // Recheck state because another thread might have
 *         // acquired write lock and changed state before we did.
 *         if (!cacheValid) {
 *           data = ...
 *           cacheValid = true;
 *         }
 *         // Downgrade by acquiring read lock before releasing write lock
 *         rwl.readLock().lock();
 *       } finally {
 *         rwl.writeLock().unlock(); // Unlock write, still hold read
 *       }
 *     }
 *
 *     try {
 *       use(data);
 *     } finally {
 *       rwl.readLock().unlock();
 *     }
 *   }
 ReentrantReadWriteLocks可以用来改善某些类型的Collection的某些用途中的并发性。一般来说,只有当预期集合很大,被更多的读写器线程访问,并且需要开销大于同步开销的操作时,才值得使用。例如,这里是一个使用TreeMap的类,它预计会有很大的并发访问量。

 class RWDictionary {
 *   private final Map<String, Data> m = new TreeMap<String, Data>();
 *   private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
 *   private final Lock r = rwl.readLock();
 *   private final Lock w = rwl.writeLock();
 *
 *   public Data get(String key) {
 *     r.lock();
 *     try { return m.get(key); }
 *     finally { r.unlock(); }
 *   }
 *   public String[] allKeys() {
 *     r.lock();
 *     try { return m.keySet().toArray(); }
 *     finally { r.unlock(); }
 *   }
 *   public Data put(String key, Data value) {
 *     w.lock();
 *     try { return m.put(key, value); }
 *     finally { w.unlock(); }
 *   }
 *   public void clear() {
 *     w.lock();
 *     try { m.clear(); }
 *     finally { w.unlock(); }
 *   }
 * }}
 该锁最多支持65535个递归写锁和65535读锁。试图超过这些限制的结果是 {@link错误}从锁定方法中抛出。

 我理解,基本是下面关系, Y 表示共享,N表示排斥(即独占)

        读        写
 读        Y        N

 写        N        N

 public class ReentrantReadWriteLock
        implements ReadWriteLock, java.io.Serializable {
    private static final long serialVersionUID = -6992448646407690164L;
    /** Inner class providing readlock */
    private final ReentrantReadWriteLock.ReadLock readerLock;    读锁
    /** Inner class providing writelock */
    private final ReentrantReadWriteLock.WriteLock writerLock;    写锁
    /** Performs all synchronization mechanics */
    final Sync sync;    同步器

    /**
     * Creates a new {@code ReentrantReadWriteLock} with
     * default (nonfair) ordering properties.    默认是 非公平锁
     */
    public ReentrantReadWriteLock() {
        this(false);
    }

    /**
     * Creates a new {@code ReentrantReadWriteLock} with
     * the given fairness policy.    策略是指 公平
     *
     * @param fair {@code true} if this lock should use a fair ordering policy
     */
    public ReentrantReadWriteLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
        readerLock = new ReadLock(this);
        writerLock = new WriteLock(this);
    }

    public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
    public ReentrantReadWriteLock.ReadLock  readLock()  { return readerLock; }

    /**
     * Synchronization implementation for ReentrantReadWriteLock.
     * Subclassed into fair and nonfair versions.

     ReentrantReadWriteLock的同步机制的基础实现。子类分为下面的公平和非公平版本。使用AQS状态来代表锁上的持有数量。

        跟ReentrantLock非常类似的做法,但是细节上很多成本;
     */
    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 6317671515068378041L;

        /*
         * Read vs write count extraction constants and functions.
         * Lock state is logically divided into two unsigned shorts:
         * The lower one representing the exclusive (writer) lock hold count,
         * and the upper the shared (reader) hold count.
         */
         *读写计数提取的常数和函数。
         * 锁定状态在逻辑上被分为两个无符号的short型数字。
         * 较低的一个代表独占(写人)锁持有数,较高的代表共享的(读线程)锁持有数。
         */

        static final int SHARED_SHIFT   = 16;
        static final int SHARED_UNIT    = (1 << SHARED_SHIFT);            较高的int bit位
        static final int MAX_COUNT      = (1 << SHARED_SHIFT) - 1;        最大的计数
        static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;        独占锁的掩码,因为独占锁是低位,而java默认为大端模式, 所以需要对独占计数 进行掩码计算;

        /** Returns the number of shared holds represented in count  */    返回某状态c中共享锁使用的次数
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }        相当于是获取高16位,忽略低位
        /** Returns the number of exclusive holds represented in count  */ 返回某状态c中独占锁使用的次数
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }        相当于是获取低16位,忽略高位

        /**
         * A counter for per-thread read hold counts.    每线程读取保持计数的计数器。
         * Maintained as a ThreadLocal; cached in cachedHoldCounter    作为ThreadLocal维护;缓存在cachedHoldCounter中。
         */

             顾名思义是 持有计算器; 为什么不单独的使用int count,而是单独的一个类? 因为 这个类需要在ThreadLocal缓存, 也就是 ThreadLocalHoldCounter  ,从ThreadLocalHoldCounter的用法可知,HoldCounter 仅仅用于 读操作的线程; 就是说每个线程进行读操作的时候,把它的读次数加1,并且保存在那个线程的本身的变量里面。
        static final class HoldCounter {
            int count = 0;
            // Use id, not reference, to avoid garbage retention     使用id,而不是引用,以避免垃圾保留。
            垃圾保留 是什么意思? 无法回收的垃圾!
            因为不是引用,就不会导致引用计算器的变化
            final long tid = getThreadId(Thread.currentThread());
        }

        /**
         * ThreadLocal subclass. Easiest to explicitly define for sake
         * of deserialization mechanics.
         ThreadLocal子类。最容易显式定义的是,为了去序列化机制。
         */
         ThreadLocal 的作用是把变量保存在线程对象内部的map变量中,但是这个map 即ThreadLocalMap是很特殊的,它以线程作为key; 故ThreadLocal提供的方法也很特殊 它提供了get、set(非静态方法),但是都不需要指定key,因为key 就是当前执行的线程;就是说,每个线程只能够获取自己的value,相当于是把 value 绑定到了线程上;

         ThreadLocal是需要初始化其内部的map对象的,仅仅在setInitialValue()、set(T value)的时候可以初始化;,每次get的时候,如果没有初始化,那么就进行初始化,即调用setInitialValue,然后调用initialValue方法,然后如有必要则创建map;
         ThreadLocal 还提供了remove方法,也就是把当前线程作为key,从map中删除

        static final class ThreadLocalHoldCounter
            extends ThreadLocal<HoldCounter> {
            public HoldCounter initialValue() {
                return new HoldCounter();    默认的读计数 当然是0

                initialValue 方法提供了初始值;当然这个是按照需要来的,某些情况 也可以不用提供初始值
            }
        }

        /**
         * The number of reentrant read locks held by current thread.
         * Initialized only in constructor and readObject.
         * Removed whenever a thread‘s read hold count drops to 0.

         * 当前线程持有的重入读锁的数量。
         * 只在构造函数和readObject中初始化。
         * 当线程的读取保持数下降到0时,会被移除。
         */
        private transient ThreadLocalHoldCounter readHolds;        把读操作计数 绑定到了线程上

        /**
         * The hold count of the last thread to successfully acquire
         * readLock. This saves ThreadLocal lookup in the common case
         * where the next thread to release is the last one to
         * acquire. This is non-volatile since it is just used
         * as a heuristic, and would be great for threads to cache.
         *
         * <p>Can outlive the Thread for which it is caching the read
         * hold count, but avoids garbage retention by not retaining a
         * reference to the Thread.
         *
         * <p>Accessed via a benign data race; relies on the memory
         * model‘s final field and out-of-thin-air guarantees.
          最后一个成功获取readLock的线程的保持数。这在下一个要释放的线程是最后一个获取的线程的情况下,可以节省ThreadLocal查找。这个是非易失性的,因为它只是作为启发式的,对于线程缓存来说是很好的。
         *
         <p>可以超过缓存的线程的读取保持数,但通过不保留对线程的引用来避免垃圾保留。
         *
         * <p>通过良性的数据竞赛访问;依靠内存模型的最终字段和空投保证。

         */
        private transient HoldCounter cachedHoldCounter; 读锁的缓存;  缓存什么? 缓存 最后一个成功获取资源的读锁! 为什么需要缓存起来? 可以节省ThreadLocal查找操作

        /**
         * firstReader is the first thread to have acquired the read lock.
         * firstReaderHoldCount is firstReader‘s hold count.
         *
         * <p>More precisely, firstReader is the unique thread that last
         * changed the shared count from 0 to 1, and has not released the
         * read lock since then; null if there is no such thread.
         *
         * <p>Cannot cause garbage retention unless the thread terminated
         * without relinquishing its read locks, since tryReleaseShared            这句话难以理解xxx
         * sets it to null.
         *
         * <p>Accessed via a benign data race; relies on the memory
         * model‘s out-of-thin-air guarantees for references.
         *
         * <p>This allows tracking of read holds for uncontended read
         * locks to be very cheap.

         * firstReader是第一个获得读锁的线程。
         * firstReaderHoldCount是firstReader的保持数。
         *
         * <p>更准确地说,firstReader是最后一次将共享计数从0改为1的唯一线程,并且此后没有释放过读锁;如果没有这样的线程,则为空。
         *
         <p>除非在没有放弃读锁的情况下终止线程,否则不会导致垃圾保留,因为 tryReleaseShared 将其设置为空。
         *
         * <p>通过良性的数据竞赛访问;依赖内存模型的无中生有地来保证引用。
         *
         * <p>这使得对无争议的读取锁的读取保持的跟踪非常便宜。

         relinquish         (尤指不情愿地)放弃 废除;撤回;停止
         benign                良性的 仁慈的;和蔼的;良好的
         out-of-thin-air    无中生有地
         */
        private transient Thread firstReader = null;        主要为了跟踪..
        private transient int firstReaderHoldCount;

        Sync() {    内部构造器
            readHolds = new ThreadLocalHoldCounter();
            setState(getState()); // ensures visibility of readHolds
        }

        /*
         * Acquires and releases use the same code for fair and
         * nonfair locks, but differ in whether/how they allow barging
         * when queues are non-empty.
         */
         * 获取和释放对公平锁和非公平锁 使用相同的代码,但在队列非空时 是否/怎么 允许线程的突然闯进 有所不同。

         barging    突然的闯入     驳船

        /**
         * Returns true if the current thread, when trying to acquire
         * the read lock, and otherwise eligible to do so, should block
         * because of policy for overtaking other waiting threads.         这里也是非常绕
         如果当前线程 正在试图获得读锁,以及在其他有资格的情况下这样做时,由于超越其他等待的线程的策略而应当被阻止,则返回true。

         所谓policy for overtaking other waiting threads,其实是线程的追赶机制。

        overtake    追上;赶上;超过;赶补(欠工) 超车;超越;追越

         */
        abstract boolean readerShouldBlock();    简单说就是 读操作是否应该阻塞

        /**
         * Returns true if the current thread, when trying to acquire
         * the write lock, and otherwise eligible to do so, should block
         * because of policy for overtaking other waiting threads.

         同上,读锁改成写锁
         */
        abstract boolean writerShouldBlock();

        /*
         * Note that tryRelease and tryAcquire can be called by
         * Conditions. So it is possible that their arguments contain
         * both read and write holds that are all released during a
         * condition wait and re-established in tryAcquire.        

            注意tryRelease和tryAcquire可以被条件对象下调用,所以 这两个方法的参数可能会 同时包含读和写的 持有数(这些持有数即 占用的资源量,会在条件对象的wait方法调用时释放和 在tryAcquire方法中重新获取)
            ———— 这个有点难理解; 我认为是因为一个写锁不会阻塞同线程的读锁,同时因为写锁上可以创建条件,那么写锁释放,也就是执行 tryRelease的时候, 是应该把所有这些 写锁、读锁全部释放的~!xxx

            (这么多的that,这么多的定语、补语、状语,英语不好的人,直接懵逼)
         */

         尝试释放独占资源
        protected final boolean tryRelease(int releases) {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            int nextc = getState() - releases;
            boolean free = exclusiveCount(nextc) == 0;    是否全部释放了
            if (free)
                setExclusiveOwnerThread(null);    全部释放则同时把同步器所有者置为null
            setState(nextc);
            return free;
        }

        尝试获取独占资源; 这个方法仅仅是基础实现; 可能被复写
        protected final boolean tryAcquire(int acquires) {        独占模式

            疑问,一个线程已经获取了写锁,那么它可以再次获取读锁吗?  答案,应该是true吧

            /*
             * Walkthrough:
             * 1. If read count nonzero or write count nonzero
             *    and owner is a different thread, fail.
             * 2. If count would saturate, fail. (This can only
             *    happen if count is already nonzero.)
             * 3. Otherwise, this thread is eligible for lock if
             *    it is either a reentrant acquire or
             *    queue policy allows it. If so, update state
             *    and set owner.

                步骤:
                1 如果读或写 锁的执行次数(调用次数)非0 而且 所有者 是其他线程,失败, 就是说此时不允许读也不允许写
                2 如果 次数 马上就要饱和(即次数太多了,即超过MAX_COUNT,state包含不下了), 失败(仅发生于次数已经非0)
                3 否则,如果当前线程是可重入获取 队列策略允许,那么它就是 有资格获取到执行锁操作;然后还需要更新资源的状态和设置所有者

                官方的说明感觉不好理解,我的理解是:
                    如果策略(指公平策略)允许,或者没有被占用,或已经被自己独占过,那么就看看是否足够资源, 都满足就成功

             */
            Thread current = Thread.currentThread();
            int c = getState();
            int w = exclusiveCount(c);    独占的次数; 一般来说,只能有一个线程独占吧;难道有 共享独占?
            if (c != 0) { 同步器已经有被占用
                // (Note: if c != 0 and w == 0 then shared count != 0)
                if (w == 0 || current != getExclusiveOwnerThread())    如果独占锁没有 或者刚刚好释放所有资源,且独占者非当前线程,返回false
                    return false;
                if (w + exclusiveCount(acquires) > MAX_COUNT)        如果将要饱和,则抛异常
                    throw new Error("Maximum lock count exceeded");
                // Reentrant acquire
                setState(c + acquires);    更新资源状态
                return true;            成功返回
            }
            // 执行到这里,表明还没被占用
            if (writerShouldBlock() ||        写是否应该阻塞, 对应非公平锁,不会阻塞;对应公平锁需要检查队列前面是否还有等待的线程
                !compareAndSetState(c, c + acquires))    或者不能 cas资源状态 成功; 成功则意味着没有竞争失败,也就是说 语义逻辑没有被其他线程的竞争破坏; 破坏了当然就应该失败
                return false;    就返回false
            setExclusiveOwnerThread(current);
            return true;
        }

        尝试释放共享资源
        protected final boolean tryReleaseShared(int unused) {    这里的参数 这个方法没用到
            Thread current = Thread.currentThread();
            if (firstReader == current) {    如果最后一次读操作就是当前线程,那么就直接的释放
                // assert firstReaderHoldCount > 0;
                if (firstReaderHoldCount == 1)
                    firstReader = null;
                else
                    firstReaderHoldCount--;
            } else {    如果不是
                HoldCounter rh = cachedHoldCounter;                    获取缓存的读计数
                if (rh == null || rh.tid != getThreadId(current))    如果不是当前线程
                    rh = readHolds.get();                            就从线程变量中获取
                int count = rh.count;
                if (count <= 1) {            如果读计数<= 1,那么就从线程变量中移除
                    readHolds.remove();
                    if (count <= 0)        不应该小于0
                        throw unmatchedUnlockException();
                }
                --rh.count;    释放一个资源
            }
            for (;;) {        try操作应该是立即返回的,为什么这里需要 自旋?因为 state是不断变化的,需要确保释放一定能够成功!!
                int c = getState();
                int nextc = c - SHARED_UNIT;    为什么要减去一个SHARED_UNIT?
                if (compareAndSetState(c, nextc))    自旋,直到成功cas
                    // Releasing the read lock has no effect on readers,
                    // but it may allow waiting writers to proceed if
                    // both read and write locks are now free.
                    return nextc == 0;
            }
        }

        private IllegalMonitorStateException unmatchedUnlockException() {
            return new IllegalMonitorStateException(
                "attempt to unlock read lock, not locked by current thread");
        }

          独占读获取到资源的时候, 使用 compareAndSetState(c, c + acquires)
        而共享读获取到资源的时候, 使用 compareAndSetState(c, c + SHARED_UNIT)
        ———— 为什么这样做? 这是需要保证共享操作,发生在高位~! 逻辑上我需要共享计数增加1,但是实际操作的时候,我们需要增加1+SHARED_UNIT,确保低位不会变;操作反应在高位, 对低位操作来说1就是1,对于高位操作来说1 就是 SHARED_UNIT, 一定要理解这一点!! ———— 释放的时候也是一样的做法;

        unused 参数如其名,是没有用到的,为什么? 因为这个类中,每次只能获取、释放一个资源~!故方法内部其实使用了1 来替代参数; 那为什么tryAcquire 方法不是如此?参照tryRelease方法,因为它们上面的条件队列 可能同时存在读计数、写计数~~!!

        protected final int tryAcquireShared(int unused) {    共享模式获取
            /*
             * Walkthrough:
             * 1. If write lock held by another thread, fail.
             * 2. Otherwise, this thread is eligible for
             *    lock wrt state, so ask if it should block
             *    because of queue policy. If not, try
             *    to grant by CASing state and updating count.
             *    Note that step does not check for reentrant
             *    acquires, which is postponed to full version
             *    to avoid having to check hold count in
             *    the more typical non-reentrant case.
             * 3. If step 2 fails either because thread
             *    apparently not eligible or CAS fails or count
             *    saturated, chain to version with full retry loop.

                步骤:
                1 如果写锁的所有者 是其他线程,失败, 就是说此时有写操作,不再允许读操作
                2 否则,如果当前线程 有资格锁定 写的部分资源,那么依据公平性检查是否应该阻塞; 如果没有资格,那么通过cas方式修改
                    注意: 当前方法不会检查可重入性;这种检查被延迟到了完全版本 以避免对更加典型的非可重入情况的检查(这样性能会牺牲比较大,得不偿失)
                3  如果 因为 明显的不合适或者 马上就要饱和,那么升级切换到 完全版本

                eligible 有资格    即readerShouldBlock返回true
             */
            Thread current = Thread.currentThread();
            int c = getState();
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
            int r = sharedCount(c);
            if (!readerShouldBlock() &&        是否应该读阻塞; 如果应该读阻塞 意味着需要去排队,应该返回负数
                r < MAX_COUNT &&            没有饱和
                compareAndSetState(c, c + SHARED_UNIT)) {    且cas成功
                if (r == 0) {    第一个读
                    firstReader = current;
                    firstReaderHoldCount = 1;
                } else if (firstReader == current) {
                    firstReaderHoldCount++;     上次读线程 就是 自己
                } else {
                    HoldCounter rh = cachedHoldCounter;    获取缓存的读计数
                    if (rh == null || rh.tid != getThreadId(current))
                        cachedHoldCounter = rh = readHolds.get();    重新设置 获取缓存的读计数
                    else if (rh.count == 0)
                        readHolds.set(rh);    // 这里不是很懂xxx
                    rh.count++;    计数+1
                }
                return 1;
            }
            return fullTryAcquireShared(current);    升级到 完全版本
        }

        /**
         * Full version of acquire for reads, that handles CAS misses    额外处理了cas失败、可重入读
         * and reentrant reads not dealt with in tryAcquireShared.
         */
        final int fullTryAcquireShared(Thread current) {
            /*
             * This code is in part redundant with that in
             * tryAcquireShared but is simpler overall by not
             * complicating tryAcquireShared with interactions between
             * retries and lazily reading hold counts.
                这些代码和tryAcquireShared方法部分冗余了,但是总体而言更加简单了,因为它没有把tryAcquireShared和 在重试及延迟的读计数 之间的交互 搞得很复杂;
             */
            HoldCounter rh = null;
            for (;;) {
                int c = getState();
                if (exclusiveCount(c) != 0) {
                    if (getExclusiveOwnerThread() != current)
                        return -1;
                    // else we hold the exclusive lock; blocking here
                    // would cause deadlock.
                } else if (readerShouldBlock()) {
                    // Make sure we‘re not acquiring read lock reentrantly
                    if (firstReader == current) {    当前线程就是最后那个读线程, 那么肯定是允许获取
                        // assert firstReaderHoldCount > 0;
                    } else {
                        if (rh == null) {
                            rh = cachedHoldCounter;
                            if (rh == null || rh.tid != getThreadId(current)) {
                                rh = readHolds.get();
                                if (rh.count == 0)
                                    readHolds.remove();
                            }
                        }
                        if (rh.count == 0)
                            return -1;        如果,, 那就阻止。
                    }
                }
                if (sharedCount(c) == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                if (compareAndSetState(c, c + SHARED_UNIT)) {            自旋+cas 会保证成功
                    if (sharedCount(c) == 0) {
                        firstReader = current;
                        firstReaderHoldCount = 1;
                    } else if (firstReader == current) {
                        firstReaderHoldCount++;
                    } else {
                        if (rh == null)
                            rh = cachedHoldCounter;
                        if (rh == null || rh.tid != getThreadId(current))
                            rh = readHolds.get();
                        else if (rh.count == 0)
                            readHolds.set(rh);
                        rh.count++;
                        cachedHoldCounter = rh; // cache for release
                    }
                    return 1;
                }
            }
        }

        /**
         * Performs tryLock for write, enabling barging in both modes.
         * This is identical in effect to tryAcquire except for lack
         * of calls to writerShouldBlock.
            准备执行写锁; 允许在两个模式下都可以闯入; 这个方法等效于 tryAcquire 除去 缺少 writerShouldBlock

            因为 它不需要问writerShouldBlock,就是true;
         */
        final boolean tryWriteLock() {
            Thread current = Thread.currentThread();
            int c = getState();
            if (c != 0) {
                int w = exclusiveCount(c);
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                if (w == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
            }
            执行到这里,表明 c==0 或者 c != 0且w!=0 而且 当前线程正在独占 —— 表明要么是没有被占用,要么就是自己占用; 非常的“专断”
            if (!compareAndSetState(c, c + 1))
                return false;
            setExclusiveOwnerThread(current);
            return true;
        }

        /**
         * Performs tryLock for read, enabling barging in both modes.
         * This is identical in effect to tryAcquireShared except for
         * lack of calls to readerShouldBlock.

            准备执行读锁; 允许在两个模式下都可以闯入; 这个方法等效于 tryAcquireShared 除了 缺少readerShouldBlock

            因为 它不需要问readerShouldBlock,就是true;
         */
        final boolean tryReadLock() {
            Thread current = Thread.currentThread();
            for (;;) {
                int c = getState();
                if (exclusiveCount(c) != 0 &&    如果已经被独占
                    getExclusiveOwnerThread() != current)    并且独占者不是自己
                    return false;    返回失败
                int r = sharedCount(c);        共享读的计数
                if (r == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");        溢出
                if (compareAndSetState(c, c + SHARED_UNIT)) {            cas成功
                    if (r == 0) {    如果读计数为0,也就是说 还没有读锁
                        firstReader = current;
                        firstReaderHoldCount = 1;
                    } else if (firstReader == current) {
                        firstReaderHoldCount++;
                    } else {
                        HoldCounter rh = cachedHoldCounter;
                        if (rh == null || rh.tid != getThreadId(current))
                            cachedHoldCounter = rh = readHolds.get();    找到当前线程对应的计数器
                        else if (rh.count == 0)
                            readHolds.set(rh);
                        rh.count++;    计数器++
                    }
                    return true;
                }
            }
        }

        protected final boolean isHeldExclusively() {
            // While we must in general read state before owner,
            // we don‘t need to do so to check if current thread is owner
            return getExclusiveOwnerThread() == Thread.currentThread();        当前线程是不是独占所有者
        }

        // Methods relayed to outer class    

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

        final Thread getOwner() {
            // Must read state before owner to ensure memory consistency
            return ((exclusiveCount(getState()) == 0) ?
                    null :
                    getExclusiveOwnerThread());
        }

        final int getReadLockCount() {
            return sharedCount(getState());
        }

        final boolean isWriteLocked() {    为什么没有getWriteLockCount 方法,因为不需要,isWriteLocked就足够
            return exclusiveCount(getState()) != 0;        WriteLock只有一个,也就是只有 存在不存在的区别
        }

        final int getWriteHoldCount() {    可以认为是写锁 重入的次数
            return isHeldExclusively() ? exclusiveCount(getState()) : 0;
        }

        final int getReadHoldCount() {
            if (getReadLockCount() == 0)
                return 0;

            Thread current = Thread.currentThread();
            if (firstReader == current)
                return firstReaderHoldCount;    可以认为是 当前线程的读锁的重入的次数

            HoldCounter rh = cachedHoldCounter;
            if (rh != null && rh.tid == getThreadId(current))
                return rh.count;    xxx

            int count = readHolds.get().count;
            if (count == 0) readHolds.remove();        为什么要删除,不删除也没用
            return count;
        }

        /**
         * Reconstitutes the instance from a stream (that is, deserializes it).
         */
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            readHolds = new ThreadLocalHoldCounter();
            setState(0); // reset to unlocked state
        }

        final int getCount() { return getState(); }
    }

    /**
     * Nonfair version of Sync
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = -8159625535654395037L;

        final boolean writerShouldBlock() {
            return false; // writers can always barge    永远都不阻塞,说明写的优先级很高
        }

        final boolean readerShouldBlock() {    复写Sync
            /* 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();
        }
    }

    /**
     * Fair version of Sync
     */
    static final class FairSync extends Sync {

        private static final long serialVersionUID = -2274990926593161451L;

        final boolean writerShouldBlock() {    复写Sync的方法
            return hasQueuedPredecessors();        公平起见,需要判断是否有前任已经在等待;只要有线程在等待,那么不管它是读线程 还是写线程, 都阻塞
        }

        final boolean readerShouldBlock() {    复写Sync的方法
            return hasQueuedPredecessors();        公平起见,需要判断是否有前任已经在等待;只要有线程在等待,那么不管它是读线程 还是写线程, 都阻塞
            why? 因为
        }
    }

    /**
     * The lock returned by method {@link ReentrantReadWriteLock#readLock}.
     */
     读锁
    public static class ReadLock implements Lock, java.io.Serializable {
        private static final long serialVersionUID = -5992448646407690164L;
        private final Sync sync;

        /**
         * Constructor for use by subclasses    其实 并没有观察到子类
         *
         * @param lock the outer lock object    外部锁对象
         * @throws NullPointerException if the lock is null
         */
        protected ReadLock(ReentrantReadWriteLock lock) {
            sync = lock.sync;
        }

        /**
         * Acquires the read lock.    获取读锁
         *
         * <p>Acquires the read lock if the write lock is not held by
         * another thread and returns immediately.
            如果写锁没有被其他线程占用,那么立即成功返回;
         *
         * <p>If the write lock is held by another thread then
         * the current thread becomes disabled for thread scheduling
         * purposes and lies dormant until the read lock has been acquired.
            如果写锁没有被其他线程占用,那么阻塞, 直到获取成功;
         */
        public void lock() {    不响应中断, 注意方法签名没有异常
            sync.acquireShared(1);
        }

        /**
         * Acquires the read lock unless the current thread is
         * {@linkplain Thread#interrupt interrupted}.
         *
         * <p>Acquires the read lock if the write lock is not held
         * by another thread and returns immediately.
         *
         * <p>If the write lock is held by another thread then the
         * current thread becomes disabled for thread scheduling
         * purposes and lies dormant until one of two things happens:
         *
         * <ul>
         *
         * <li>The read lock is acquired by the current thread; or
         *
         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
         * the current thread.
         *
         * </ul>
         *
         * <p>If the current thread:
         *
         * <ul>
         *
         * <li>has its interrupted status set on entry to this method; or
         *
         * <li>is {@linkplain Thread#interrupt interrupted} while
         * acquiring the read lock,
         *
         * </ul>
         *
         * then {@link InterruptedException} is thrown and the current
         * thread‘s interrupted status is cleared.
         *
         * <p>In this implementation, as this method is an explicit
         * interruption point, preference is given to responding to
         * the interrupt over normal or reentrant acquisition of the
         * lock.
         *
         * @throws InterruptedException if the current thread is interrupted
         */
         同上,但是 抛异常的方式 响应中断 , 注意方法签名 有中断异常
        public void lockInterruptibly() throws InterruptedException {
            sync.acquireSharedInterruptibly(1);
        }

        /**
         * Acquires the read lock only if the write lock is not held by
         * another thread at the time of invocation.
            如果写锁没有被其他线程占用,那么立即成功返回;
         *
         * <p>Acquires the read lock if the write lock is not held by
         * another thread and returns immediately with the value
         * {@code true}. Even when this lock has been set to use a
         * fair ordering policy, a call to {@code tryLock()}
         * <em>will</em> immediately acquire the read lock if it is
         * available, whether or not other threads are currently
         * waiting for the read lock.  This &quot;barging&quot; behavior
         * can be useful in certain circumstances, even though it
         * breaks fairness. If you want to honor the fairness setting
         * for this lock, then use {@link #tryLock(long, TimeUnit)
         * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent
         * (it also detects interruption).
            如果写锁没有被其他线程占用,那么立即成功返回;read lock 不会阻塞read lock,它们可以共享; 但是如果read lock 被阻塞,说明存在write lock; 这个方法允许线程突然的闯入,会破坏一定的公平性(但是如果要保证更好的公平,可以使用tryLock(0, TimeUnit.SECONDS))
         *
         * <p>If the write lock is held by another thread then
         * this method will return immediately with the value
         * {@code false}.
            如果写锁被其他线程占用,那么立即失败返回
         *
         * @return {@code true} if the read lock was acquired
         */
        public boolean tryLock() {
            return sync.tryReadLock();
        }

        /**
         * Acquires the read lock if the write lock is not held by
         * another thread within the given waiting time and the
         * current thread has not been {@linkplain Thread#interrupt
         * interrupted}.
         *
         * <p>Acquires the read lock if the write lock is not held by
         * another thread and returns immediately with the value
         * {@code true}. If this lock has been set to use a fair
         * ordering policy then an available lock <em>will not</em> be
         * acquired if any other threads are waiting for the
         * lock. This is in contrast to the {@link #tryLock()}
         * method. If you want a timed {@code tryLock} that does
         * permit barging on a fair lock then combine the timed and
         * un-timed forms together:
         *
         *  <pre> {@code
         * if (lock.tryLock() ||
         *     lock.tryLock(timeout, unit)) {
         *   ...
         * }}</pre>
         *
         * <p>If the write lock is held by another thread then the
         * current thread becomes disabled for thread scheduling
         * purposes and lies dormant until one of three things happens:
         *
         大致同上,但同时响应中断和超时
         */
        public boolean tryLock(long timeout, TimeUnit unit)
                throws InterruptedException {
            return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));    尝试锁定一个资源
        }

        /**
         * Attempts to release this lock.
         *
         * <p>If the number of readers is now zero then the lock
         * is made available for write lock attempts.
         */
        public void unlock() {
            sync.releaseShared(1);    释放一个资源; 如果读锁已经完全释放了,那么写锁也是可以进入了
        }

        /**
         * Throws {@code UnsupportedOperationException} because
         * {@code ReadLocks} do not support conditions.
         *
         * @throws UnsupportedOperationException always
         */
        public Condition newCondition() {
            throw new UnsupportedOperationException(); 读锁不支持条件,why? 因为AQS的内部类Condition 只支持独占模式
        }

        /**
         * Returns a string identifying this lock, as well as its lock state.
         * The state, in brackets, includes the String {@code "Read locks ="}
         * followed by the number of held read locks.
         *
         * @return a string identifying this lock, as well as its lock state
         */
        public String toString() {
            int r = sync.getReadLockCount();
            return super.toString() +
                "[Read locks = " + r + "]";
        }
    }

    /**
     * The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
     */
    public static class WriteLock implements Lock, java.io.Serializable {
        private static final long serialVersionUID = -4992448646407690164L;
        private final Sync sync;

        /**
         * Constructor for use by subclasses
         *
         * @param lock the outer lock object
         * @throws NullPointerException if the lock is null
         */
        protected WriteLock(ReentrantReadWriteLock lock) {
            sync = lock.sync;
        }

        /**
         * Acquires the write lock.
         *
         * <p>Acquires the write lock if neither the read nor write lock
         * are held by another thread
         * and returns immediately, setting the write lock hold count to
         * one.
            如果写锁没有被其他线程 读或者写(其实就是所有情况),那么立即成功返回,随后写计数置为1;

         *
         * <p>If the current thread already holds the write lock then the
         * hold count is incremented by one and the method returns
         * immediately.
            如果写锁已经被当前线程占有,那么立即成功返回,随后写计数 +1;
         *
         * <p>If the lock is held by another thread then the current
         * thread becomes disabled for thread scheduling purposes and
         * lies dormant until the write lock has been acquired, at which
         * time the write lock hold count is set to one.
            如果写锁已经被其他线程占有,那么陷入阻塞,直到成功获取 写锁;
         */
        public void lock() {
            sync.acquire(1);     阻塞式获取一个资源
        }

        /**
         * Acquires the write lock unless the current thread is
         * {@linkplain Thread#interrupt interrupted}.
         *
         * <p>Acquires the write lock if neither the read nor write lock
         * are held by another thread
         * and returns immediately, setting the write lock hold count to
         * one.
         *
         * <p>If the current thread already holds this lock then the
         * hold count is incremented by one and the method returns
         * immediately.
         *
         * <p>If the lock is held by another thread then the current
         * thread becomes disabled for thread scheduling purposes and
         * lies dormant until one of two things happens:
         *

         大致同上,但响应中断
        public void lockInterruptibly() throws InterruptedException {
            sync.acquireInterruptibly(1);
        }

        /**
         * Acquires the write lock only if it is not held by another thread
         * at the time of invocation.
         *
         * <p>Acquires the write lock if neither the read nor write lock
         * are held by another thread
         * and returns immediately with the value {@code true},
         * setting the write lock hold count to one. Even when this lock has
         * been set to use a fair ordering policy, a call to
         * {@code tryLock()} <em>will</em> immediately acquire the
         * lock if it is available, whether or not other threads are
         * currently waiting for the write lock.  This &quot;barging&quot;
         * behavior can be useful in certain circumstances, even
         * though it breaks fairness. If you want to honor the
         * fairness setting for this lock, then use {@link
         * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
         * which is almost equivalent (it also detects interruption).
         *
         * <p>If the current thread already holds this lock then the
         * hold count is incremented by one and the method returns
         * {@code true}.
         *
         * <p>If the lock is held by another thread then this method
         * will return immediately with the value {@code false}.
         *
         * @return {@code true} if the lock was free and was acquired
         * by the current thread, or the write lock was already held
         * by the current thread; and {@code false} otherwise.
         */
         立即返回成功、或者失败,
        public boolean tryLock( ) {
            return sync.tryWriteLock();        非阻塞式获取一个资源
        }

        /**
         * Acquires the write lock if it is not held by another thread
         * within the given waiting time and the current thread has
         * not been {@linkplain Thread#interrupt interrupted}.
         *
         * <p>Acquires the write lock if neither the read nor write lock
         * are held by another thread
         * and returns immediately with the value {@code true},
         * setting the write lock hold count to one. If this lock has been
         * set to use a fair ordering policy then an available lock
         * <em>will not</em> be acquired if any other threads are
         * waiting for the write lock. This is in contrast to the {@link
         * #tryLock()} method. If you want a timed {@code tryLock}
         * that does permit barging on a fair lock then combine the
         * timed and un-timed forms together:
         *
         *  <pre> {@code
         * if (lock.tryLock() ||
         *     lock.tryLock(timeout, unit)) {
         *   ...
         * }}</pre>
         *
         * <p>If the current thread already holds this lock then the
         * hold count is incremented by one and the method returns
         * {@code true}.
         *
         * <p>If the lock is held by another thread then the current
         * thread becomes disabled for thread scheduling purposes and
         * lies dormant until one of three things happens: 

         大致同上,但同时响应中断和超时
        public boolean tryLock(long timeout, TimeUnit unit)
                throws InterruptedException {
            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
        }

        /**
         * Attempts to release this lock.
         *
         * <p>If the current thread is the holder of this lock then
         * the hold count is decremented. If the hold count is now
         * zero then the lock is released.  If the current thread is
         * not the holder of this lock then {@link
         * IllegalMonitorStateException} is thrown.
         *
         * @throws IllegalMonitorStateException if the current thread does not
         * hold this lock
         */

        public void unlock() {
            sync.release(1);    释放一个资源; 如果 已经完全释放了,那么相当于所有锁都已经释放
        }

        /**
         * Returns a {@link Condition} instance for use with this
         * {@link Lock} instance.
         * <p>The returned {@link Condition} instance supports the same
         * usages as do the {@link Object} monitor methods ({@link
         * Object#wait() wait}, {@link Object#notify notify}, and {@link
         * Object#notifyAll notifyAll}) when used with the built-in
         * monitor lock.
         *
         * <ul>
         *
         * <li>If this write lock is not held when any {@link
         * Condition} method is called then an {@link
         * IllegalMonitorStateException} is thrown.  (Read locks are
         * held independently of write locks, so are not checked or
         * affected. However it is essentially always an error to
         * invoke a condition waiting method when the current thread
         * has also acquired read locks, since other threads that
         * could unblock it will not be able to acquire the write
         * lock.)
         *
         * <li>When the condition {@linkplain Condition#await() waiting}
         * methods are called the write lock is released and, before
         * they return, the write lock is reacquired and the lock hold
         * count restored to what it was when the method was called.
         *
         * <li>If a thread is {@linkplain Thread#interrupt interrupted} while
         * waiting then the wait will terminate, an {@link
         * InterruptedException} will be thrown, and the thread‘s
         * interrupted status will be cleared.
         *
         * <li> Waiting threads are signalled in FIFO order.
         *
         * <li>The ordering of lock reacquisition for threads returning
         * from waiting methods is the same as for threads initially
         * acquiring the lock, which is in the default case not specified,
         * but for <em>fair</em> locks favors those threads that have been
         * waiting the longest.
         *
         * </ul>
         *
         * @return the Condition object
         */
        public Condition newCondition() {
            return sync.newCondition();
        }

        /**
         * Returns a string identifying this lock, as well as its lock
         * state.  The state, in brackets includes either the String
         * {@code "Unlocked"} or the String {@code "Locked by"}
         * followed by the {@linkplain Thread#getName name} of the owning thread.
         *
         * @return a string identifying this lock, as well as its lock state
         */
        public String toString() {
            Thread o = sync.getOwner();
            return super.toString() + ((o == null) ?
                                       "[Unlocked]" :
                                       "[Locked by thread " + o.getName() + "]");
        }

        /**
         * Queries if this write lock is held by the current thread.
         * Identical in effect to {@link
         * ReentrantReadWriteLock#isWriteLockedByCurrentThread}.
         *
         * @return {@code true} if the current thread holds this lock and
         *         {@code false} otherwise
         * @since 1.6
         */
        public boolean isHeldByCurrentThread() { 等效于ReentrantReadWriteLock.isWriteLockedByCurrentThread
            return sync.isHeldExclusively();
        }

        /**
         * Queries the number of holds on this write lock by the current
         * thread.  A thread has a hold on a lock for each lock action
         * that is not matched by an unlock action.  Identical in effect
         * to {@link ReentrantReadWriteLock#getWriteHoldCount}.
         *
         * @return the number of holds on this lock by the current thread,
         *         or zero if this lock is not held by the current thread
         * @since 1.6
         */
        public int getHoldCount() {
            return sync.getWriteHoldCount();    等效于ReentrantReadWriteLock.getWriteHoldCount
        }
    }

    // Instrumentation and status

    /**
     * Returns {@code true} if this lock has fairness set true.
     *
     * @return {@code true} if this lock has fairness set true
     */
    public final boolean isFair() {
        return sync instanceof FairSync;    是否公平
    }

    /**
     * Returns the thread that currently owns the write lock, or
     * {@code null} if not owned. When this method is called by a
     * thread that is not the owner, the return value reflects a
     * best-effort approximation of current lock status. For example,
     * the owner may be momentarily {@code null} even if there are
     * threads trying to acquire the lock but have not yet done so.
     * This method is designed to facilitate construction of
     * subclasses that provide more extensive lock monitoring
     * facilities.
     *
     * @return the owner, or {@code null} if not owned
     */
    protected Thread getOwner() {
        return sync.getOwner();        返回最大努力的结果
    }

    /**
     * Queries the number of read locks held for this lock. This
     * method is designed for use in monitoring system state, not for
     * synchronization control.
     * @return the number of read locks held
     */
     用于系统状态监控
    public int getReadLockCount() {
        return sync.getReadLockCount();
    }

    /**
     * Queries if the write lock is held by any thread. This method is
     * designed for use in monitoring system state, not for
     * synchronization control.
        被设计用于系统状态监控,why?就是说只在系统状态相关函数中被调用
     *
     * @return {@code true} if any thread holds the write lock and
     *         {@code false} otherwise
     */
    public boolean isWriteLocked() {
        return sync.isWriteLocked();
    }

    /**
     * Queries if the write lock is held by the current thread.

     *
     * @return {@code true} if the current thread holds the write lock and
     *         {@code false} otherwise
     */
    public boolean isWriteLockedByCurrentThread() {
        return sync.isHeldExclusively();
    }

    /**
     * Queries the number of reentrant write holds on this lock by the
     * current thread.  A writer thread has a hold on a lock for
     * each lock action that is not matched by an unlock action.
        查询写锁的重入次数,没有unlock之前,写线程在每次lock操作的时候增加一个计数,
     *
     * @return the number of holds on the write lock by the current thread,
     *         or zero if the write lock is not held by the current thread
     */
    public int getWriteHoldCount() {
        return sync.getWriteHoldCount();
    }

    /**
     * Queries the number of reentrant read holds on this lock by the
     * current thread.  A reader thread has a hold on a lock for
     * each lock action that is not matched by an unlock action.
        查询读锁的重入次数
     *
     * @return the number of holds on the read lock by the current thread,
     *         or zero if the read lock is not held by the current thread
     * @since 1.6
     */
    public int getReadHoldCount() {
        return sync.getReadHoldCount();
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire the write lock.  Because the actual set of threads may
     * change dynamically while constructing this result, the returned
     * collection is only a best-effort estimate.  The elements of the
     * returned collection are in no particular order.  This method is
     * designed to facilitate construction of subclasses that provide
     * more extensive lock monitoring facilities.
     *
     * @return the collection of threads
     */
     获取队列中等待获取写锁的线程的集合,返回最大努力
    protected Collection<Thread> getQueuedWriterThreads() {
        return sync.getExclusiveQueuedThreads();
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire the read lock.  Because the actual set of threads may
     * change dynamically while constructing this result, the returned
     * collection is only a best-effort estimate.  The elements of the
     * returned collection are in no particular order.  This method is
     * designed to facilitate construction of subclasses that provide
     * more extensive lock monitoring facilities.
     *
     * @return the collection of threads
     */
     获取队列中等待获取读锁的线程的集合,返回最大努力
    protected Collection<Thread> getQueuedReaderThreads() {
        return sync.getSharedQueuedThreads();
    }

    /**
     * Queries whether any threads are waiting to acquire the read or
     * write lock. Note that because cancellations may occur at any
     * time, a {@code true} return does not guarantee that any other        ,返回最大努力
     * thread will ever acquire a lock.  This method is designed
     * primarily for use in monitoring of the system state.
     *
     * @return {@code true} if there may be other threads waiting to
     *         acquire the lock
     */
     获取队列中是否有 等待获取的线程
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /**
     * Queries whether the given thread is waiting to acquire either
     * the read or write lock. Note that because cancellations may
     * occur at any time, a {@code true} return does not guarantee        ,返回最大努力
     * that this thread will ever acquire a lock.  This method is
     * designed primarily for use in monitoring of the system state.
     *
     * @param thread the thread
     * @return {@code true} if the given thread is queued waiting for this lock
     * @throws NullPointerException if the thread is null
     */
     获取队列中是否有 等待获取的线程
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    /**
     * Returns an estimate of the number of threads waiting to acquire
     * either the read or write lock.  The value is only an estimate        ,返回最大努力
     * because the number of threads may change dynamically while this
     * method traverses internal data structures.  This method is
     * designed for use in monitoring of the system state, not for
     * synchronization control.
     *
     * @return the estimated number of threads waiting for this lock
     */
    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire either the read or write lock.  Because the actual set
     * of threads may change dynamically while constructing this
     * result, the returned collection is only a best-effort estimate.        ,返回最大努力
     * The elements of the returned collection are in no particular
     * order.  This method is designed to facilitate construction of
     * subclasses that provide more extensive monitoring facilities.
     *
     * @return the collection of threads
     */
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    /**
     * Queries whether any threads are waiting on the given condition
     * associated with the write lock. Note that because timeouts and
     * interrupts may occur at any time, a {@code true} return does
     * not guarantee that a future {@code signal} will awaken any        ,返回最大努力
     * threads.  This method is designed primarily for use in
     * monitoring of the system state.
     *
     * @param condition the condition
     * @return {@code true} if there are any waiting threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    public boolean hasWaiters(Condition condition) {    返回写锁对象条件上的 等待者
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns an estimate of the number of threads waiting on the
     * given condition associated with the write lock. Note that because
     * timeouts and interrupts may occur at any time, the estimate
     * serves only as an upper bound on the actual number of waiters.        ,返回最大努力
     * This method is designed for use in monitoring of the system
     * state, not for synchronization control.
     *
     * @param condition the condition
     * @return the estimated number of waiting threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns a collection containing those threads that may be
     * waiting on the given condition associated with the write lock.
     * Because the actual set of threads may change dynamically while
     * constructing this result, the returned collection is only a        ,返回最大努力
     * best-effort estimate. The elements of the returned collection
     * are in no particular order.  This method is designed to
     * facilitate construction of subclasses that provide more
     * extensive condition monitoring facilities.
     *
     * @param condition the condition
     * @return the collection of threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns a string identifying this lock, as well as its lock state.
     * The state, in brackets, includes the String {@code "Write locks ="}
     * followed by the number of reentrantly held write locks, and the
     * String {@code "Read locks ="} followed by the number of held
     * read locks.
     *
     * @return a string identifying this lock, as well as its lock state
     */
    public String toString() {
        int c = sync.getCount();
        int w = Sync.exclusiveCount(c);
        int r = Sync.sharedCount(c);

        return super.toString() +
            "[Write locks = " + w + ", Read locks = " + r + "]";
    }

    /**
     * Returns the thread id for the given thread.  We must access
     * this directly rather than via method Thread.getId() because
     * getId() is not final, and has been known to be overridden in
     * ways that do not preserve unique mappings.
     */
    static final long getThreadId(Thread thread) {
        return UNSAFE.getLongVolatile(thread, TID_OFFSET);
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe UNSAFE;
    private static final long TID_OFFSET;
    static {
        try {
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> tk = Thread.class;
            TID_OFFSET = UNSAFE.objectFieldOffset
                (tk.getDeclaredField("tid"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

}

这个类 还是比较难理解的,主要在于可重入的理解,条件对象的支持,已经锁的降级与升级;

原文地址:https://www.cnblogs.com/FlyAway2013/p/12663748.html

时间: 2024-10-11 11:05:26

被面试官吊打系列之JUC之 可重入读写锁ReentrantReadWriteLock 之 源码详尽分析的相关文章

自定义View系列教程03--onLayout源码详尽分析

PS:如果觉得文章太长,那就直接看视频吧 在经过measure阶段以后,系统确定了View的测量大小,接下来就进入到layout的过程. 在该过程中会确定视图的显示位置,即子View在其父控件中的位置. 嗯哼,我们直接扒开源码从View的layout( )开始入手. //l, t, r, b分别表示子View相对于父View的左.上.右.下的坐标 public void layout(int l, int t, int r, int b) { if ((mPrivateFlags3 & PFLA

自定义View系列教程02--onMeasure源码详尽分析

PS:如果觉得文章太长,那就直接看视频吧 大家知道,自定义View有三个重要的步骤:measure,layout,draw.而measure处于该链条的首端,占据着极其重要的地位:然而对于measure的理解却不是那么容易,许多问题都是一知半解,比如:为什么父View影响到了子View的MeasureSpec的生成?为什么我们自定义一个View在布局时将其宽或者高指定为wrap_content但是其实际是match_parent的效果?子View的specMode和specSize的生成依据又是

JUC同步器框架AbstractQueuedSynchronizer源码图文分析

JUC同步器框架AbstractQueuedSynchronizer源码图文分析 前提 Doug Lea大神在编写JUC(java.util.concurrent)包的时候引入了java.util.concurrent.locks.AbstractQueuedSynchronizer,Abstract Queued Synchronizer,也就是"基于队列实现的抽象同步器",一般我们称之为AQS.其实Doug Lea大神编写AQS是有严谨的理论基础的,他的个人博客上有一篇论文<

JUC包中的CountDownLatch源码实现分析

CountDownLatch是JUC包中提供的线程同步工具,使用CountDownLatch可以实现一个或多个线程等待直到一组操作在其他线程中被执行完成. CountDownLatch基于AQS实现,代码不多,所以很好分析.本文只分析CountDownLatch实现, 关于AQS的实现在另外一篇文章中叙述. 下面是CountDownLatch的类图: 接下来贴上来CountDownLatch的源码: public class CountDownLatch { private static fin

【原创】源码角度分析Android的消息机制系列(一)——Android消息机制概述

ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 1.为什么需要Android的消息机制 因为Android系统不允许在子线程中去访问UI,即Android系统不允许在子线程中更新UI. 为什么不允许在子线程中更新UI呢?因为Android的控件不是线程安全的.既然是非线程安全的,那么若在多个子线程中并发访问,UI控制可能会处于一种不可预期的状态.有的读者可能会说,为什么不对UI控件加锁呢?加锁会降低UI访问的效率,因为加锁之后,若想要运行这段synchronized的代码,线程要先拿到

广告行业中那些趣事系列2:BERT实战NLP文本分类任务(附github源码)

摘要:上一篇广告中那些趣事系列1:广告统一兴趣建模流程,我们了解了如何为广告主圈人群以及如何刻画用户的兴趣度.要想给用户打标签,我们需要构建数据源和标签的关联,也就是item-tag.针对数量较少的app数据源我们可以使用人工打标的方式来识别,但是对于news.用户query等数量较多的数据源则需要通过机器学习模型来进行打标.实际项目中我们使用NLP中鼎鼎大名的BERT模型来进行文本分类. 通过本篇学习,小伙伴们可以迅速上手BERT模型用于文本分类任务.对数据挖掘.数据分析和自然语言处理感兴趣的

【原创】源码角度分析Android的消息机制系列(六)——Handler的工作原理

ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 先看Handler的定义: /** * A Handler allows you to send and process {@link Message} and Runnable * objects associated with a thread's {@link MessageQueue}. Each Handler * instance is associated with a single thread and that thre

【原创】源码角度分析Android的消息机制系列(五)——Looper的工作原理

ι 版权声明:本文为博主原创文章,未经博主允许不得转载. Looper在Android的消息机制中就是用来进行消息循环的.它会不停地循环,去MessageQueue中查看是否有新消息,如果有消息就立刻处理该消息,否则就一直等待. Looper中有一个属性: static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); 这也就解释了,前面我们所说的我们可以通过ThreadLocal实现Looper

【原创】源码角度分析Android的消息机制系列(四)——MessageQueue的工作原理

ι 版权声明:本文为博主原创文章,未经博主允许不得转载. MessageQueue,主要包含2个操作:插入和读取.读取操作会伴随着删除操作,插入和读取对应的方法分别为enqueueMessage和next,其中enqueueMessage的作用是往消息队列中插入一条消息,而next的作用是从消息队列中取出一条消息并将其从消息队列中移除.虽然MessageQueue叫消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单链表的数据结构来维护消息列表,单链表在插入和删除上比较有优势. 先看M