ReentrantReadWriteLock分析

概述

ReentrantReadWriteLock是Lock的另一種實現方式烈和,我們已經知道了ReentrantLock是一個排他鎖,同一時間只允許一個線程訪問皿淋,而ReentrantReadWriteLock允許多個讀線程同時訪問招刹,但不允許寫線程和讀線程恬试、寫線程和寫線程同時訪問。相對于排他鎖疯暑,提高了并發(fā)性训柴。在實際應用中,大部分情況下對共享數據(如緩存)的訪問都是讀操作遠多于寫操作妇拯,這時ReentrantReadWriteLock能夠提供比排他鎖更好的并發(fā)性和吞吐量幻馁。
另外
1.ReentrantReadWriteLock支持鎖的降級,即先獲取寫鎖越锈,再獲取讀鎖仗嗦,再釋放寫鎖。
2.讀鎖不支持Condition甘凭,會拋出UnsupportedOperationException異常稀拐,寫鎖支持Condition。

讀鎖的獲取

state的高16位讀鎖總共獲取的次數(包括每個線程重入的次數)丹弱,對于每個讀線程的重入次數保存在ThreadLocalHoldCounter中钩蚊。
低16位保存寫鎖的狀態(tài)。

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.
             */
            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)) {
                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);
                    rh.count++;
                }
                return 1;
            }
            return fullTryAcquireShared(current);
        }

讀鎖是否需要阻塞蝠咆,在公平鎖中,如果同步隊列中有阻塞的節(jié)點就阻塞北滥,在非公平鎖中刚操,如果隊列中有寫線程節(jié)點就阻塞,目的是防止寫線程饑餓再芋。

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;
    }

如果讀線程需要阻塞菊霜,或者獲取資源失敗,執(zhí)行fullTryAcquireShared

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;
                }
            }
        }

注意tryAcquireShared返回值济赎,返回值大于0表示獲取到資源鉴逞,小于0沒有獲取到資源

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

自旋獲取資源,獨占鎖在獲取到資源以后不會有向下傳遞的行為,共享鎖在獲取到資源以后,會向下傳遞喚醒阻塞的其他共享線程写半。

private void setHeadAndPropagate(Node node, int propagate) {
        Node h = head; // Record old head for check below
        setHead(node);
        /*
         * Try to signal next queued node if:
         *   Propagation was indicated by caller,
         *     or was recorded (as h.waitStatus either before
         *     or after setHead) by a previous operation
         *     (note: this uses sign-check of waitStatus because
         *      PROPAGATE status may transition to SIGNAL.)
         * and
         *   The next node is waiting in shared mode,
         *     or we don't know, because it appears null
         *
         * The conservatism in both of these checks may cause
         * unnecessary wake-ups, but only when there are multiple
         * racing acquires/releases, so most need signals now or soon
         * anyway.
         */
        if (propagate > 0 || h == null || h.waitStatus < 0 ||
            (h = head) == null || h.waitStatus < 0) {
            Node s = node.next;
            if (s == null || s.isShared())
                doReleaseShared();
        }
    }
private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        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
            }
            //如果頭節(jié)點有變化也就是有其他線程獲取到了資源爱榕,繼續(xù)循環(huán)向下傳遞
            if (h == head)                   // loop if head changed
                break;
        }
    }

對于共享鎖的傳播,如果隊列中有一個非共享節(jié)點,則到此停止傳播。為什么s==null也會執(zhí)行doReleaseShared贫橙?這樣可能會喚醒一些沒必要喚醒的節(jié)點喘帚,但是考慮在這個時間段會有比較多的讀線程畅姊,所以也會執(zhí)行doReleaseShared,對在執(zhí)行doReleaseShared期間加入到當前節(jié)點后面的線程做一次unpark吹由,就可以是后繼節(jié)點不阻塞涡匀,直接獲取資源。
然后將頭節(jié)點狀態(tài)設置為PROPAGATE溉知,保證能夠進入if (propagate > 0 || h == null || h.waitStatus < 0 || (h = head) == null || h.waitStatus < 0)

讀鎖的釋放

public void unlock() {
            sync.releaseShared(1);
        }
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陨瘩,0就移除,不為0減少重入的次數
                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;
            }
            //自旋更新state的狀態(tài)
            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;
            }
        }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末级乍,一起剝皮案震驚了整個濱河市舌劳,隨后出現的幾起案子,更是在濱河造成了極大的恐慌玫荣,老刑警劉巖甚淡,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異捅厂,居然都是意外死亡贯卦,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門焙贷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來撵割,“玉大人,你說我怎么就攤上這事辙芍》缺颍” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵故硅,是天一觀的道長庶灿。 經常有香客問我,道長吃衅,這世上最難降的妖魔是什么往踢? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮徘层,結果婚禮上峻呕,老公的妹妹穿的比我還像新娘。我一直安慰自己惑灵,他們只是感情好山上,可當我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著英支,像睡著了一般。 火紅的嫁衣襯著肌膚如雪哮伟。 梳的紋絲不亂的頭發(fā)上干花,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天妄帘,我揣著相機與錄音,去河邊找鬼池凄。 笑死抡驼,一個胖子當著我的面吹牛,可吹牛的內容都是我干的肿仑。 我是一名探鬼主播致盟,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼尤慰!你這毒婦竟也來了馏锡?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤伟端,失蹤者是張志新(化名)和其女友劉穎杯道,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體责蝠,經...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡党巾,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了霜医。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片齿拂。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖肴敛,靈堂內的尸體忽然破棺而出创肥,到底是詐尸還是另有隱情,我是刑警寧澤值朋,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布叹侄,位于F島的核電站,受9級特大地震影響昨登,放射性物質發(fā)生泄漏趾代。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一丰辣、第九天 我趴在偏房一處隱蔽的房頂上張望撒强。 院中可真熱鬧,春花似錦笙什、人聲如沸飘哨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽芽隆。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間胚吁,已是汗流浹背牙躺。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留腕扶,地道東北人孽拷。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像半抱,于是被迫代替她去往敵國和親脓恕。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內容

  • ReentrantLock 介紹 一個可重入的互斥鎖窿侈,它具有與使用{synchronized}方法和語句訪問的隱式...
    tomas家的小撥浪鼓閱讀 4,056評論 1 4
  • 第三章 Java內存模型 3.1 Java內存模型的基礎 通信在共享內存的模型里炼幔,通過寫-讀內存中的公共狀態(tài)進行隱...
    澤毛閱讀 4,352評論 2 22
  • 每一個閃光的人,都在不為人知的地方默默努力棉磨。穿越孤獨江掩,戰(zhàn)勝恐懼,完善自己乘瓤。誰都希望順遂安逸环形,但止步不前,生命何來意...
    成長共勉之閱讀 152評論 0 0
  • #一大早第二次被撞 大運# 鬼使神差地難得開車上班衙傀,前兩天聽說我聲音像「歡樂晚高峰」里的"小舅媽"抬吟,結果一大早沒聽...
    古靈精怪小摩女閱讀 226評論 0 0
  • 琺瑯彩起始于康熙后期火本,頂盛時為雍正期至乾隆期。但雍正期的琺瑯彩水平最高聪建,工藝最美钙畔。乾隆時期慢慢轉向粉彩,故琺瑯彩終...
    骨玩閱讀 204評論 0 0