一步步透徹理解Lock的Acquire和Release原理源碼

Java中已知的鎖有兩種贰军,一種是synchronized塑悼,另一種是Lock馋嗜;這兩種的基本原理在之前的文章中已經(jīng)做了分析:

深入理解Synchronized實(shí)現(xiàn)原理
java AQS的實(shí)現(xiàn)原理

這次我們從最常用的Lock也就是ReentrantLock的Acquire和Release鎖的過(guò)程入手辐啄,一步一步的跟源代碼,探究獲取鎖和釋放鎖的步驟景鼠。

獲取鎖

ReentrantLock lock=new ReentrantLock();
lock.lock();
1.lock()

上面代碼是我們常用的獲取鎖的方式:調(diào)用ReentrantLock 的lock()方法仲翎,默認(rèn)情況下ReentrantLock是一個(gè)非公平鎖,類名NonfairSync莲蜘,屬于ReentrantLock的內(nèi)部類谭确,我們來(lái)看源碼:

static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

這里的lock方法先去通過(guò)CAS操作將state的值從0變?yōu)?,(注:ReentrantLock用state表示“持有鎖的線程已經(jīng)重復(fù)獲取該鎖的次數(shù)”票渠。當(dāng)state等于0時(shí)逐哈,表示當(dāng)前沒(méi)有線程持有鎖),如果成功问顷,就設(shè)置ExclusiveOwnerThread的值為當(dāng)前線程(Exclusive是獨(dú)占的意思昂秃,ReentrantLock用exclusiveOwnerThread表示“持有鎖的線程”)禀梳。
如果設(shè)置失敗,說(shuō)明state>0已經(jīng)有線程持有了鎖肠骆,此時(shí)執(zhí)行acquire(1)再請(qǐng)求一次鎖算途。

2.acquire()
/**
     * Acquires in exclusive mode, ignoring interrupts.  Implemented
     * by invoking at least once {@link #tryAcquire},
     * returning on success.  Otherwise the thread is queued, possibly
     * repeatedly blocking and unblocking, invoking {@link
     * #tryAcquire} until success.  This method can be used
     * to implement method {@link Lock#lock}.
     *
     * @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();
    }

這里我們注意一下acquire方法上面的注釋,已經(jīng)說(shuō)得很清楚了蚀腿,這里我大概說(shuō)下我的理解:

請(qǐng)求獨(dú)占鎖嘴瓤,忽略所有中斷,至少執(zhí)行一次tryAcquire莉钙,如果成功就返回廓脆,否則線程進(jìn)入阻塞--喚醒兩種狀態(tài)切換中,直到tryAcquire成功磁玉。

我們對(duì)里面的tryAcquire()停忿,、addWaiter()蚊伞、acquireQueued()挨個(gè)分析席赂。
在這個(gè)方法里先執(zhí)行tryAcquire(arg):

3.tryAcquire()
final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

先判斷state是否為0,如果為0就執(zhí)行上面提到的lock方法的前半部分时迫,通過(guò)CAS操作將state的值從0變?yōu)?颅停,否則判斷當(dāng)前線程是否為exclusiveOwnerThread,然后把state++别垮,也就是重入鎖的體現(xiàn)便监,我們注意前半部分是通過(guò)CAS來(lái)保證同步扎谎,后半部分并沒(méi)有同步的體現(xiàn)碳想,原因是:

后半部分是線程重入,再次獲得鎖時(shí)才觸發(fā)的操作毁靶,此時(shí)當(dāng)前線程擁有鎖胧奔,所以對(duì)ReentrantLock的屬性操作是無(wú)需加鎖的。

如果tryAcquire()獲取失敗预吆,則要執(zhí)行addWaiter()向等待隊(duì)列中添加一個(gè)獨(dú)占模式的節(jié)點(diǎn)

4.addWaiter()
/**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */
    private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }

這個(gè)方法的注釋:創(chuàng)建一個(gè)入隊(duì)node為當(dāng)前線程龙填,Node.EXCLUSIVE 是獨(dú)占鎖, Node.SHARED 是共享鎖。
先找到等待隊(duì)列的tail節(jié)點(diǎn)pred拐叉,如果pred岩遗!=null,就把當(dāng)前線程添加到pred后面進(jìn)入等待隊(duì)列凤瘦,如果不存在tail節(jié)點(diǎn)執(zhí)行enq()

private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

這里進(jìn)行了循環(huán)宿礁,如果此時(shí)存在了tail就執(zhí)行同上一步驟的添加隊(duì)尾操作,如果依然不存在蔬芥,就把當(dāng)前線程作為head結(jié)點(diǎn)梆靖。
插入節(jié)點(diǎn)后控汉,調(diào)用acquireQueued()進(jìn)行阻塞

5.acquireQueued()
final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

先獲取當(dāng)前節(jié)點(diǎn)的前一節(jié)點(diǎn)p,如果p是head的話就再進(jìn)行一次tryAcquire(arg)操作返吻,如果成功就返回姑子,否則就執(zhí)行shouldParkAfterFailedAcquire、parkAndCheckInterrupt來(lái)達(dá)到阻塞效果测僵;

6.shouldParkAfterFailedAcquire()
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
             * need a signal, but don't park yet.  Caller will need to
             * retry to make sure it cannot acquire before parking.
             */
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

addWaiter()構(gòu)造的新節(jié)點(diǎn)街佑,waitStatus的默認(rèn)值是0。此時(shí)捍靠,進(jìn)入最后一個(gè)if判斷舆乔,CAS設(shè)置pred.waitStatus為SIGNAL==-1。最后返回false剂公。

回到第五步acquireQueued()中后希俩,由于shouldParkAfterFailedAcquire()返回false,會(huì)繼續(xù)進(jìn)行循環(huán)纲辽。假設(shè)node的前繼節(jié)點(diǎn)pred仍然不是頭結(jié)點(diǎn)或鎖獲取失敗颜武,則會(huì)再次進(jìn)入shouldParkAfterFailedAcquire()。上一輪循環(huán)中拖吼,已經(jīng)將pred.waitStatus設(shè)置為SIGNAL==-1鳞上,則這次會(huì)進(jìn)入第一個(gè)判斷條件,直接返回true吊档,表示應(yīng)該阻塞篙议。

7.parkAndCheckInterrupt()
private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }

很顯然,一旦shouldParkAfterFailedAcquire返回true也就是應(yīng)該阻塞怠硼,就會(huì)執(zhí)行parkAndCheckInterrupt()來(lái)達(dá)到阻塞效果鬼贱,此時(shí)線程阻塞在這里,需要其它線程來(lái)喚醒香璃,喚醒后就會(huì)再次循環(huán)第5步acquireQueued里的請(qǐng)求邏輯这难。

我們回到第6步,看一個(gè)留下的邏輯片段

if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } 

什么時(shí)候會(huì)遇到ws > 0的case呢葡秒?當(dāng)pred所維護(hù)的獲取請(qǐng)求被取消時(shí)(也就是node的waitStatus 值為CANCELLED)姻乓,這時(shí)就會(huì)循環(huán)移除所有被取消的前繼節(jié)點(diǎn)pred,直到找到未被取消的pred眯牧。移除所有被取消的前繼節(jié)點(diǎn)后蹋岩,直接返回false。

8.cancelAcquire()

到這里我們回到第5步可以看到主體邏輯基本走完了学少,在該方法的finally里有一個(gè)cancelAcquire()方法

private void cancelAcquire(Node node) {
        // Ignore if node doesn't exist
        if (node == null)
            return;

        node.thread = null;

        // Skip cancelled predecessors
        Node pred = node.prev;
        while (pred.waitStatus > 0)
            node.prev = pred = pred.prev;

        // predNext is the apparent node to unsplice. CASes below will
        // fail if not, in which case, we lost race vs another cancel
        // or signal, so no further action is necessary.
        Node predNext = pred.next;

        // Can use unconditional write instead of CAS here.
        // After this atomic step, other Nodes can skip past us.
        // Before, we are free of interference from other threads.
        node.waitStatus = Node.CANCELLED;

        // If we are the tail, remove ourselves.
        if (node == tail && compareAndSetTail(node, pred)) {
            compareAndSetNext(pred, predNext, null);
        } else {
            // If successor needs signal, try to set pred's next-link
            // so it will get one. Otherwise wake it up to propagate.
            int ws;
            if (pred != head &&
                ((ws = pred.waitStatus) == Node.SIGNAL ||
                 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
                pred.thread != null) {
                Node next = node.next;
                if (next != null && next.waitStatus <= 0)
                    compareAndSetNext(pred, predNext, next);
            } else {
                unparkSuccessor(node);
            }

            node.next = node; // help GC
        }
    }

也就是在第5步的執(zhí)行過(guò)程中剪个,如果出現(xiàn)異常或者出現(xiàn)中斷旱易,就會(huì)執(zhí)行finally的取消線程的請(qǐng)求操作禁偎,核心代碼是node.waitStatus = Node.CANCELLED;將線程的狀態(tài)改為CANCELLED腿堤。

釋放鎖

1.release()
/**
     * Releases in exclusive mode.  Implemented by unblocking one or
     * more threads if {@link #tryRelease} returns true.
     * This method can be used to implement method {@link Lock#unlock}.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryRelease} but is otherwise uninterpreted and
     *        can represent anything you like.
     * @return the value returned from {@link #tryRelease}
     */
    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

我們還是通過(guò)方法上面的注釋來(lái)理解一下:
釋放獨(dú)占鎖,如果tryRelease成功返回true的話就會(huì)解開(kāi)阻塞等待的線程
顯然如暖,tryRelease方法來(lái)釋放鎖笆檀,如果釋放成功,先判斷head節(jié)點(diǎn)是否有效盒至,最后unparkSuccessor啟動(dòng)后續(xù)等待的線程酗洒。

2.tryRelease()
protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

先獲取state減去釋放的一次,然后判斷當(dāng)前線程是否和持有鎖線程一致枷遂,如果不一致樱衷,拋出異常,繼續(xù)判斷state的值酒唉,只有當(dāng)值為0時(shí)矩桂,free標(biāo)志才置為true,否則說(shuō)明是重入鎖痪伦,需要多次釋放直到state為0侄榴。

3.unparkSuccessor()
private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
            LockSupport.unpark(s.thread);
    }

這個(gè)方法名:?jiǎn)?dòng)后續(xù)線程,先拿到head節(jié)點(diǎn)的waitStatus并清空网沾,然后獲取next節(jié)點(diǎn)癞蚕,并做檢查,如果next節(jié)點(diǎn)失效辉哥,就從等待隊(duì)列的尾部進(jìn)行輪詢桦山,拿到第一個(gè)有效的節(jié)點(diǎn),然后通過(guò)LockSupport.unpark(s.thread);喚醒醋旦,令該線程重新進(jìn)入到獲取鎖的第5步循環(huán)去acquire鎖恒水。

疑惑點(diǎn)

1.我們?cè)讷@取鎖的很多步驟中看到tryAcquire的操作,原因是當(dāng)獲取一次失敗后浑度,程序會(huì)去執(zhí)行失敗后的邏輯代碼寇窑,但是在執(zhí)行過(guò)程中有可能鎖的狀態(tài)也同時(shí)發(fā)生了變化(釋放鎖鸦概、pred節(jié)點(diǎn)失效等情況)箩张,這時(shí)候需要去tryAcquire一下,省去了阻塞再喚醒的成本窗市。
2.等待隊(duì)列的waitStatus屬性使用很多先慷,在這里我們先讀一下源碼注釋:

/** waitStatus value to indicate thread has cancelled */
        static final int CANCELLED =  1;
        /** waitStatus value to indicate successor's thread needs unparking */
        static final int SIGNAL    = -1;
        /** waitStatus value to indicate thread is waiting on condition */
        static final int CONDITION = -2;
        /**
         * waitStatus value to indicate the next acquireShared should
         * unconditionally propagate
         */
        static final int PROPAGATE = -3;

        /**
         * Status field, taking on only the values:
         *   SIGNAL:     The successor of this node is (or will soon be)
         *               blocked (via park), so the current node must
         *               unpark its successor when it releases or
         *               cancels. To avoid races, acquire methods must
         *               first indicate they need a signal,
         *               then retry the atomic acquire, and then,
         *               on failure, block.
         *   CANCELLED:  This node is cancelled due to timeout or interrupt.
         *               Nodes never leave this state. In particular,
         *               a thread with cancelled node never again blocks.
         *   CONDITION:  This node is currently on a condition queue.
         *               It will not be used as a sync queue node
         *               until transferred, at which time the status
         *               will be set to 0. (Use of this value here has
         *               nothing to do with the other uses of the
         *               field, but simplifies mechanics.)
         *   PROPAGATE:  A releaseShared should be propagated to other
         *               nodes. This is set (for head node only) in
         *               doReleaseShared to ensure propagation
         *               continues, even if other operations have
         *               since intervened.
         *   0:          None of the above
         *
         * The values are arranged numerically to simplify use.
         * Non-negative values mean that a node doesn't need to
         * signal. So, most code doesn't need to check for particular
         * values, just for sign.
         *
         * The field is initialized to 0 for normal sync nodes, and
         * CONDITION for condition nodes.  It is modified using CAS
         * (or when possible, unconditional volatile writes).
         */
        volatile int waitStatus;

SIGNAL:后續(xù)線程正在阻塞,所以當(dāng)前node在釋放鎖時(shí)必須啟動(dòng)后續(xù)線程咨察,為了避免競(jìng)爭(zhēng)激烈论熙,acquire 方法第一次執(zhí)行需要一個(gè)信號(hào),也就是這個(gè)啟動(dòng)信號(hào)摄狱。
CANCELLED:這個(gè)node失效了脓诡,因?yàn)槌瑫r(shí)或者被中斷等原因无午。
CONDITION:這個(gè)node當(dāng)前是屬于條件鎖
PROPAGATE:這個(gè)node是共享鎖節(jié)點(diǎn),他需要進(jìn)行喚醒傳播

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末祝谚,一起剝皮案震驚了整個(gè)濱河市宪迟,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌交惯,老刑警劉巖次泽,帶你破解...
    沈念sama閱讀 222,183評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異席爽,居然都是意外死亡意荤,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)只锻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)玖像,“玉大人,你說(shuō)我怎么就攤上這事齐饮∮澹” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,766評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵沈矿,是天一觀的道長(zhǎng)上真。 經(jīng)常有香客問(wèn)我,道長(zhǎng)羹膳,這世上最難降的妖魔是什么睡互? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,854評(píng)論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮陵像,結(jié)果婚禮上就珠,老公的妹妹穿的比我還像新娘。我一直安慰自己醒颖,他們只是感情好妻怎,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著泞歉,像睡著了一般逼侦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上腰耙,一...
    開(kāi)封第一講書(shū)人閱讀 52,457評(píng)論 1 311
  • 那天榛丢,我揣著相機(jī)與錄音,去河邊找鬼挺庞。 笑死晰赞,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播掖鱼,決...
    沈念sama閱讀 40,999評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼然走,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了戏挡?” 一聲冷哼從身側(cè)響起丰刊,我...
    開(kāi)封第一講書(shū)人閱讀 39,914評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎增拥,沒(méi)想到半個(gè)月后啄巧,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,465評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡掌栅,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評(píng)論 3 342
  • 正文 我和宋清朗相戀三年秩仆,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片猾封。...
    茶點(diǎn)故事閱讀 40,675評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡澄耍,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出晌缘,到底是詐尸還是另有隱情齐莲,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評(píng)論 5 351
  • 正文 年R本政府宣布磷箕,位于F島的核電站选酗,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏岳枷。R本人自食惡果不足惜芒填,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望空繁。 院中可真熱鬧殿衰,春花似錦、人聲如沸盛泡。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,514評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)傲诵。三九已至凯砍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間掰吕,已是汗流浹背果覆。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,616評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留殖熟,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,091評(píng)論 3 378
  • 正文 我出身青樓斑响,卻偏偏與公主長(zhǎng)得像菱属,于是被迫代替她去往敵國(guó)和親钳榨。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評(píng)論 2 360