ReentrantReadWriteLock原始碼分析

pb_yan發表於2018-06-05

     ReentrantLock中,執行緒都是以獨佔的方式來獲得鎖,但是在很多情況下,比如讀多寫少的情況,使用獨佔的方式明顯不合適,讀和讀之間不會修改共享資源,可以保證不會出現問題,這種情況下使用ReentrantReadWriteLock會更合適。讀執行緒之間使用共享鎖,寫寫和寫讀之間使用獨佔鎖。ReentrantReadWriteLock的類結構如下圖所示:


      其中Syn實現了AQS中的一些比較重要的方法,比如lock和release,這裡包括獨佔的方式和共享的方式兩種。NonfairSyn和FairSyn是公平鎖和非公平鎖的實現,主要包括兩個方法。ReadLock和WriteLock是對Syn類中的方法進行再一次的封裝,函式體都非常簡單。

特性

1.公平性:讀操作之間不互斥,所以沒有公平非公平這麼一說。寫操作在非公平鎖中,寫鎖總是最先獲得鎖。而在公平鎖中,只根據在CLH佇列中等待的時間來分配鎖。

2.重入性:讀操作獲得讀鎖之後可以再次獲得讀鎖,寫鎖同理。但是讀鎖不能被寫鎖重入,寫鎖可以獲得讀鎖,這就是鎖降級。

3.可中斷:提供可以響應中斷的鎖。

引數及建構函式

    /** 通過內部類來獲得讀鎖 */
    private final ReentrantReadWriteLock.ReadLock readerLock;
    /** 獲得寫鎖*/
    private final ReentrantReadWriteLock.WriteLock writerLock;
    /** Performs all synchronization mechanics */
    final Sync sync;

    /**
     * 預設是非公平鎖,因為這樣吞吐量更大.
     */
    public ReentrantReadWriteLock() {
        this(false);
    }

    /**
     * 可以在建構函式中設定公平或者是非公平
     * @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);
    }

和reentrantLock不一樣的地方在於把原來的state拆成了兩份。

  /*
         *通過將state狀態分為高16位和低16位來分別代表讀鎖的佔有量和寫鎖的佔有量
         */

        static final int SHARED_SHIFT   = 16;
        static final int SHARED_UNIT    = (1 << SHARED_SHIFT);
        static final int MAX_COUNT      = (1 << SHARED_SHIFT) - 1;
        static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;

        /** 獲得共享鎖佔有的次數  */
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
        /** 獲取獨佔鎖重入的次數  */
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }

寫鎖的讀取和釋放

寫鎖由於是獨佔鎖,其獲取和釋放相對讀鎖更加簡單。寫鎖的獲取和釋放都在Syn中實現。

  首先會獲得當前鎖的數量,然後在通過位操作獲得相應的寫鎖個數,並根據相應條件進行判斷是否這個執行緒可以獲得寫鎖。

 /**
     * 獲得鎖成功則退出,不成功則新增節點到CLH佇列尾部,然後執行acquireQueued迴圈嘗試獲取鎖,這裡和reentrantLock 類似。
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     */
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
protected final int tryAcquireShared(int unused) { //嘗試獲取資源 /* * */
        Thread current = Thread.currentThread();
        int c = getState();
        if (exclusiveCount(c) != 0 && //當期寫鎖不為0 或者是寫鎖佔有了執行緒 返回-1 
                getExclusiveOwnerThread() != current)
            return -1;
        int r = sharedCount(c);//獲取讀鎖 
        if (!readerShouldBlock() && r < MAX_COUNT && compareAndSetState(c, c + SHARED_UNIT)) {
            if (r == 0) {
                firstReader = current;
                firstReaderHoldCount = 1;//讀鎖個數為0 設定頭讀節點和持有數量 
            } 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 1;
        }
        return fullTryAcquireShared(current);//讀鎖被阻塞導致的失敗,繼續執行下面函式來獲取鎖 }

    }
 protected final boolean tryAcquire(int acquires) {
            /*
             * Walkthrough:
             * 1. 讀鎖個數不是0或者寫鎖個數不是0或者當前執行緒不是持有鎖的執行緒,失敗。
             * 2. 如果鎖個數大於最大值,失敗
             * 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.
             */
            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())
                    return false;//讀鎖不為0,寫鎖為0,失敗
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");//個數太多,失敗
                // Reentrant acquire
                setState(c + acquires);//其他都是成功,返回新的狀態值
                return true;
            }
            if (writerShouldBlock() || //鎖的個數為0 判斷是否需要阻塞 ,write總是返回false
                !compareAndSetState(c, c + acquires))
                return false;
            setExclusiveOwnerThread(current);//設定排他執行緒。
            return true;
        }
寫鎖釋放也比較簡單,判斷執行緒是否正確,判斷鎖的個數是否為0.
 /*
         * 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.
         */

        protected final boolean tryRelease(int releases) {
            if (!isHeldExclusively())//如果當前執行緒不是持有執行緒則丟擲異常。
                throw new IllegalMonitorStateException();
            int nextc = getState() - releases;//重新計算鎖的個數
            boolean free = exclusiveCount(nextc) == 0;//鎖的個數中低16位鎖個數為0 則設定排他執行緒為空
            if (free)
                setExclusiveOwnerThread(null);
            setState(nextc);
            return free;
        }



讀鎖的獲取比較複雜。下面是讀鎖獲取的簡單流程。


 /**
     * 忽略中斷,以共享的模式獲取鎖  Implemented by
     * first invoking at least once {@link #tryAcquireShared},
     * returning on success.  Otherwise the thread is queued, possibly
     * repeatedly blocking and unblocking, invoking {@link
     * #tryAcquireShared} until success.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquireShared} but is otherwise uninterpreted
     *        and can represent anything you like.
     */
    public final void acquireShared(int arg) {
        if (tryAcquireShared(arg) < 0)//嘗試獲取鎖,如果沒有獲得,就做一些嘗試操作
            doAcquireShared(arg);
    }
   /**
         * Full version of acquire for reads, that handles CAS misses
         * 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.
             */
            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()) {//寫鎖為0 讀鎖幾遍被阻塞也要執行,不然死鎖
                    // 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;
                    }
                }//成功獲取讀鎖,如果是頭讀節點則狀態加一,否則和tryAcquired成功獲取鎖一樣。
                if (sharedCount(c) == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                if (compareAndSetState(c, c + SHARED_UNIT)) {//設定狀態
                    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;
                }
            }
        }

 /**
     * 讀鎖獲取資源失敗後,新增這個執行緒作為一個節點放在後面,然後不斷獲取前驅節點,當前驅節點是head節點時,嘗試獲取資源
     * 否則,判斷當前執行緒是不是應該阻塞,然後阻塞之。
     */
    private void doAcquireShared(int arg) {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        if (interrupted)
                            selfInterrupt();
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }


   讀鎖的釋放相對簡單,首先嚐試釋放資源,如果可以的話嘗試喚醒後繼節點。嘗試釋放資源的過程中,如果當前節點是頭讀節點,並且持有鎖的數量為1,那麼釋放資源之後頭讀節點就是null了,否則將持有節點數量減一。


 /**
     * Releases in shared mode.  Implemented by unblocking one or more
     * threads if {@link #tryReleaseShared} returns true.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryReleaseShared} but is otherwise uninterpreted
     *        and can represent anything you like.
     * @return the value returned from {@link #tryReleaseShared}
     */
    public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }
  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) {
                    readHolds.remove();
                    if (count <= 0)
                        throw unmatchedUnlockException();
                }
                --rh.count;
            }
            for (;;) {
                int c = getState();
                int nextc = c - SHARED_UNIT;
                if (compareAndSetState(c, nextc))
                    // 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;//如果鎖為0,可以喚醒後面的寫鎖了。
            }
        }
 /**
     * Release action for shared mode -- signals successor and ensures
     * propagation. (Note: For exclusive mode, release just amounts
     * to calling unparkSuccessor of head if it needs signal.)
     */
    private void doReleaseShared() {
        /*
         *喚醒後繼節點
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }


參考資料:

https://my.oschina.net/adan1/blog/158107

https://www.jianshu.com/p/d47fe1ec1bb3

https://www.jianshu.com/p/9f98299a17a5(寫的很詳細)

http://ifeve.com/juc-reentrantreadwritelock/




相關文章