被面試官吊打系列之JUC之 可重入讀寫鎖ReentrantReadWriteLock 之 源碼詳盡分析

可重入讀寫鎖 ReentrantReadWriteLock 其實基本上模擬了文件的讀寫鎖操做。ReentrantReadWriteLock 和ReentrantLock 的差異仍是蠻大的; 可是也有不少的類似之處; ReentrantReadWriteLock 的 writerLock 其實就是至關於ReentrantLock,可是它提供更多的細膩的控制;理解什麼是讀鎖、寫鎖很是重要,雖然實際工做中區分讀寫鎖這樣的細分使用場景比較少。java

 

ReentrantReadWriteLock 把鎖進行了細化,分爲了兩種: 讀鎖和寫鎖。它們之間有一些限制關係:緩存

  讀  寫
讀   Y    N
寫   N    N
併發

其中: Y 表示共享,N表示排斥(即獨佔)app

 

具體分析以下less

/**
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);
        }
    }

}

 

這個類 仍是比較難理解的,主要在於可重入的理解,條件對象的支持,已經鎖的降級與升級;ide

相關文章
相關標籤/搜索