《Java後端知識體系》系列之共享鎖 ReentrantReadWriteLock的原理

上次說了ReentrantLock這次說ReentrantReadWriteLock

解決線程安全問題使用ReentrantLock,但是ReentrantLock是獨佔鎖,同一時刻只有一個線程可以獲得鎖,而實際中會有寫多讀少的場景,因此ReentrantLock滿足不了這個需求,所以ReentrantReadWriteLock應運而生,ReentrantReadWriteLock採用讀寫分離策略,允許多個線程同時獲得鎖。
以下是ReentrantReadWriteLock的類圖
在這裏插入圖片描述
從類圖中我們可以看到ReentrantReadWriteLock中實現了WriteLock和ReadLock,依賴於了Sync實現具體功能(繼承AQS來實現),同時也分爲公平鎖和非公平鎖。

我們知道在AQS中維護了一個state狀態值,通過狀態值來判斷鎖的狀態,而ReentrantReadWriteLock則需要維護讀狀態和寫狀態,那麼一個state如何表示讀狀態和寫狀態呢,ReentrantReadWriteLock使用了state的高低位來實現,通過高16位表示讀狀態,也就是讀鎖的可重入次數,低16位表示寫狀態,也就是寫鎖的可重入次數。

        static final int SHARED_SHIFT   = 16;
        //共享鎖(讀鎖)狀態單位值65536
        static final int SHARED_UNIT    = (1 << SHARED_SHIFT);
        // 共享鎖線程最大個 65535
        static final int MAX_COUNT      = (1 << SHARED_SHIFT) - 1;
        //排它鎖(寫鎖)掩碼, 二進制, 15個1
        static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;

        /** Returns the number of shared holds represented in count  */
        //返回讀鎖線程數(持有讀鎖的線程數量)
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
        /** Returns the number of exclusive holds represented in count  */
        //返回寫鎖可重入次數(寫鎖被寫入的次數)
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }

其中firstReader用來記錄第一個獲取到鎖的線程,firstReaderHoldCount則記錄第一個獲取到讀鎖的線程所獲取的讀鎖的可重入次數,cachedHoldCounter用來記錄最後一個獲取讀鎖的線程所獲取的讀鎖的可重入次數。

        static final class HoldCounter {
            int count = 0;
            // Use id, not reference, to avoid garbage retention
            final long tid = getThreadId(Thread.currentThread());
        }

readHolds是ThreadLocal變量,用來存放除去第一個獲取讀鎖線程外其它線程所獲取的讀鎖的可重入次數。ThreadLocalHoldCounter繼承ThreadLocal,因而initialValue返回一個HoldCounter對象。

        static final class ThreadLocalHoldCounter
            extends ThreadLocal<HoldCounter> {
            public HoldCounter initialValue() {
                return new HoldCounter();
            }
        }

寫鎖的獲取與釋放

寫鎖是一個獨佔鎖,同一時刻只有一個線程可以獲取該鎖,如果沒有線程獲取到讀鎖和寫鎖,則當前線程可以獲取到寫鎖然後返回,如果已經有線程獲取到了讀鎖和寫鎖,那麼當前線程會被阻塞掛起。另外,寫鎖是可重入鎖,如果當前線程已經獲得了寫鎖,那麼再次該線程再次獲得寫鎖時會將state的值加1然後返回。

1、void lock()

		//調用WriteLock中的lock方法
        public void lock() {
            sync.acquire(1);
        }
	    public final void acquire(int arg) {
	    	//sync重寫tryAcquire方法
	        if (!tryAcquire(arg) &&
	            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
	            selfInterrupt();
	    }

如上代碼中在lock內部調用AQS的acquire方法,其中tryAcquire是ReentrantReadWriteLock內部的sync類重寫的,代碼如下:

        protected final boolean tryAcquire(int acquires) {
            /*
             * 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.
             */
            Thread current = Thread.currentThread();
            int c = getState();
            int w = exclusiveCount(c);
            //1、c!=0說明讀鎖或者寫鎖已經被線程獲取
            if (c != 0) {
                // (Note: if c != 0 and w == 0 then shared count != 0)
                //2、w==0說明已經有其它線程獲取了讀鎖,w!=0並且當前線程不是寫鎖的持有者,則返回false
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                    //3、說明當前線程獲取了寫鎖,判斷可重入次數
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // Reentrant acquire
                //4、設置可重入次數
                setState(c + acquires);
                return true;
            }
            //5、第一個寫線程獲取寫鎖
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            setExclusiveOwnerThread(current);
            return true;
        }

在代碼1中如果當前AQS狀態值不爲0,則說明當前讀鎖或寫鎖已經被其它線程獲取,在代碼2中如果w==0,說明狀態值低16位爲0,而AQS狀態值不爲0,則說明高16爲不爲0,說明已經有線程獲取了讀鎖,所以直接返回false。
而如果w!=0則說明已經有線程獲取了讀寫鎖,然後再判斷鎖的持有者是不是當前線程。
如果鎖的持有者是當前線程則增加可重入次數,同時也要判斷可重入次數有沒有大於最大可重入次數,如果大於則拋出異常。
如果AQS的狀態值爲0,則執行代碼5,獲取讀寫鎖,對於writerShouldBlock方法來說需要做公平以及非公平的實現,非公平的實現爲

    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = -8159625535654395037L;
        final boolean writerShouldBlock() {
            return false; // writers can always barge
        }
        final boolean readerShouldBlock() {
            /* As a heuristic to avoid indefinite writer starvation,
             * block if the thread that momentarily appears to be head
             * of queue, if one exists, is a waiting writer.  This is
             * only a probabilistic effect since a new reader will not
             * block if there is a waiting writer behind other enabled
             * readers that have not yet drained from the queue.
             */
            return apparentlyFirstQueuedIsExclusive();
        }
    }

公平的實現方式爲,依然通過hasQueuedPredecessors來判斷阻塞隊列中是否有前驅節點。

 static final class FairSync extends Sync {
        private static final long serialVersionUID = -2274990926593161451L;
        final boolean writerShouldBlock() {
            return hasQueuedPredecessors();
        }
        final boolean readerShouldBlock() {
            return hasQueuedPredecessors();
        }
    }

2、void unlock()

對於嘗試釋放鎖來說,如果當前線程是鎖的持有者,則會讓AQS的狀態值減1,如果減1之後state爲0,則會釋放鎖,否則僅僅減1.如果當前線程沒有持有鎖,則會拋出異常IllegalMonitorStateException。

        public void unlock() {
            sync.release(1);
        }

	    public final boolean release(int arg) {
	    	//調用ReentrantReadWriteLock中sync實現的release方法
	        if (tryRelease(arg)) {
	        	//激活阻塞隊列中的一個線程
	            Node h = head;
	            if (h != null && h.waitStatus != 0)
	                unparkSuccessor(h);
	            return true;
	        }
	        return false;
	    }
        protected final boolean tryRelease(int releases) {
        	//判斷是否是寫鎖的持有者調用的unlock
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            //獲取可重入值,這裏沒有考慮高16位,因此獲取寫鎖時,讀鎖的狀態肯定爲0
            int nextc = getState() - releases;
            boolean free = exclusiveCount(nextc) == 0;
            //如果寫鎖可重入值爲0則釋放鎖,否則只是簡單的更新狀態值
            if (free)
                setExclusiveOwnerThread(null);
            setState(nextc);
            return free;
        }

如上代碼中會先通過isHeldExclusively判斷當前線程是否是寫鎖的持有者,如果不是則拋出異常,如果是則獲取可重入值,然後判斷可重入次數是否爲0,爲0則釋放鎖,將鎖的持有者設爲null,否則只是將狀態值減1。

讀鎖的獲取與釋放

ReentrantReadWriteLock中的讀鎖是使用ReadLock來實現的。
1、void lock()
獲取讀鎖,如果當前沒有其它線程持有寫鎖,則當前線程可以獲取讀鎖,AQS的狀態值state的高16位的值會增加1,然後返回。否則如果其它線程持有寫鎖,則當前線程會阻塞。

    public void lock() {
         sync.acquireShared(1);
     }
     public final void acquireShared(int arg) {
	      if (tryAcquireShared(arg) < 0)
	          doAcquireShared(arg);
	 }

在如上代碼中,讀鎖lock方法調用了AQS的acquireShared方法,在其內部調用了ReentrantReadWriteLock的sync重寫的tryAcquireShared方法,代碼如下:

 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)獲取當前狀態值
            Thread current = Thread.currentThread();
            int c = getState();
            //(2)判斷寫鎖是否被佔用
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
             //(3)獲取讀鎖計數
            int r = sharedCount(c);
            //(4)嘗試獲取鎖,多個線程只有一個會成功,不成功的進入fullTryAcquireShared進行重試
            if (!readerShouldBlock() &&
                r < MAX_COUNT &&
                compareAndSetState(c, c + SHARED_UNIT)) {
                //(5)第一個線程獲取讀鎖
                if (r == 0) {
                    firstReader = current;
                    firstReaderHoldCount = 1;
                  //(6)獲取當前線程是第一個獲取讀鎖的線程
                } else if (firstReader == current) {
                    firstReaderHoldCount++;
                } else {
                	//(7)記錄最後一個獲取讀鎖的線程或記錄其它線程讀鎖的可重入數
                    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;
            }
            //(8)類似tryAcquireShared,但是是自旋獲取
            return fullTryAcquireShared(current);
        }

如上代碼中,首先獲取當前AQS的狀態值,然後代碼(2)查看其它線程是否獲取到了寫鎖,如果是則直接返回-1,而後調用AQS的doAcquireShared方法把線程放入阻塞隊列。
如果當前要獲取讀鎖的線程已經獲取了寫鎖,則也可以獲取讀鎖,但是要注意當一個線程先獲取了寫鎖,然後獲取了讀鎖處理事情完畢後,要記得把讀鎖和寫鎖都釋放掉,不能只釋放寫鎖。
否則執行代碼(3),得到獲取到的讀鎖的個數,到這裏說明目前沒有線程到寫鎖,但是可能有線程持有讀鎖,然後執行代碼(4)。其中非公平鎖的readerShouldBlock實現代碼如下:

		final boolean readerShouldBlock() {
            /* As a heuristic to avoid indefinite writer starvation,
             * block if the thread that momentarily appears to be head
             * of queue, if one exists, is a waiting writer.  This is
             * only a probabilistic effect since a new reader will not
             * block if there is a waiting writer behind other enabled
             * readers that have not yet drained from the queue.
             */
            return apparentlyFirstQueuedIsExclusive();
        }
       final boolean apparentlyFirstQueuedIsExclusive() {
        Node h, s;
        return (h = head) != null &&
            (s = h.next)  != null &&
            !s.isShared()         &&
            s.thread != null;
    }

如上代碼的作用是,如果隊列裏面存在一個元素,則判斷元素是不是正在嘗試獲取寫鎖,如果不是,則當前線程判斷當前獲取讀鎖的線程是否達到了最大值。最後執行CAS操作將AQS的狀態值的高16位減1.
代碼(5)(6)記錄第一個獲取到讀鎖的線程,並統計該線程獲取讀鎖的可重入數,代碼(7)使用cachedHoldCounter記錄最後一個獲取到讀鎖的線程和該線程獲取讀鎖的可重入數,readHolds記錄當前線程獲取到讀鎖的可重入數。
如果readerShouldBlock返回true,則說明有線程正在獲取寫鎖,所以執行代碼(8),fullTryAcquireShare的代碼與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()) {
                    // 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)) {
                    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;
                }
            }
        }

2、void unlock()

        public void unlock() {
            sync.releaseShared(1);
        }

如上代碼中具體釋放鎖的操作是委託給Syncll類來做的,sync.releaseShared方法代碼如下:

    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;
            }
            //循環直到自己的讀計數爲-1,CAS更新成功
            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;
            }
        }

如上代碼中,在無線循環裏,首先獲取當前AQS狀態值並將其保存到變量c中,然後變量c被減去一個讀計數單位後使用CAS操作更新AQS的狀態值,如果更新成功則查看當前AQS的狀態值是否爲0,爲0則說明當前已經沒有讀線程佔用讀鎖,則tryReleaseShared返回true,然後調用doReleaseShared方法釋放一個由於獲取寫鎖而被阻塞的線程,如果當前AQS的狀態值不爲0,則說明當前還有其它線程持有讀鎖,所以tryReleaseShared返回false。如果tryReleaseShared中的CAS更新AQS狀態值失敗,則自旋重試直到成功。

新增了讀鎖的部門,週末兩天陪着女朋友去了海邊曬了一天的太陽,又玩了一天休息了一天,我是懶散的湯姆,最後的最後給你們喫一波狗糧吧!
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章