【線程安全】2.2 鎖--AQS(AbstractQueuedSynchronizer)

AbstractQueuedSynchronizer,它是阻塞式鎖和相關(guān)同步器的框架。

AbstractQueuedSynchronizer 的結(jié)構(gòu)和 Monitor 對(duì)象的結(jié)構(gòu)有些類似,都有只有所得線程、阻塞隊(duì)列等。

1. 屬性與結(jié)構(gòu)

1.1 幾個(gè)重要的屬性

public abstract class AbstractQueuedSynchronizer
    extends AbstractOwnableSynchronizer
    implements java.io.Serializable {
    /**
     * Head of the wait queue, lazily initialized.  Except for
     * initialization, it is modified only via method setHead.  Note:
     * If head exists, its waitStatus is guaranteed not to be
     * CANCELLED.
     */
    private transient volatile Node head;

    /**
     * Tail of the wait queue, lazily initialized.  Modified only via
     * method enq to add new wait node.
     */
    private transient volatile Node tail;

    /**
     * The synchronization state.
     */
    private volatile int state;
public abstract class AbstractOwnableSynchronizer
    implements java.io.Serializable {
    /**
     * The current owner of exclusive mode synchronization.
     */
    private transient Thread exclusiveOwnerThread;

加上從 AbstractOwnableSynchronizer 繼承來的屬性,這里重點(diǎn)關(guān)注的是以下四個(gè)屬性:

state: 正整數(shù),表示鎖的狀態(tài),0 表示沒有被占用,1 表示被占用,大于 1 則表示重入的次數(shù)。

head: Node 類型的對(duì)象,阻塞隊(duì)列的頭結(jié)點(diǎn),頭結(jié)點(diǎn)是無意義的,只是用來連接,也被稱為啞元或哨兵

tail: Node 類型的對(duì)象,阻塞隊(duì)列的尾結(jié)點(diǎn)

exclusiveOwnerThread: 當(dāng)前持有鎖的線程

1.2 內(nèi)部類

  1. 雙向阻塞隊(duì)列的節(jié)點(diǎn)類
static final class Node {
        /** Marker to indicate a node is waiting in shared mode */
        static final Node SHARED = new Node();
        /** Marker to indicate a node is waiting in exclusive mode */
        static final Node EXCLUSIVE = null;

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

        volatile Node prev;

        volatile Node next;

        volatile Thread thread;

        Node nextWaiter;

Node 是鏈表(類似于 monitor 的 entryList)的節(jié)點(diǎn)類,上面提到的 head、tail 都是這個(gè)類型對(duì)象。每個(gè)阻塞的線程都用 Node 封裝起來構(gòu)成一個(gè)鏈表節(jié)點(diǎn)加在隊(duì)尾。

除了前驅(qū)節(jié)點(diǎn)、后繼節(jié)點(diǎn),還有以下幾個(gè)屬性:
waitStatus:線程的等待狀態(tài)
thread:用于存儲(chǔ)阻塞的線程
SHARED:new Node(),靜態(tài)常量,代表共享鎖
EXCLUSIVE:值為 null,是靜態(tài)常量,代表排它鎖
nextWaiter:下一個(gè)節(jié)點(diǎn),ConditionObject 專用。prev、next 是 AQS 阻塞隊(duì)列專用。

AQS 阻塞隊(duì)列是雙向鏈表(prev、next),ConditionObject 中的隊(duì)列是單向鏈表(nextWaiter)

其中 waitStatus 的幾種狀態(tài):
CANCELLED:值為 1,代表取消等待,除了這個(gè)狀態(tài),其他幾個(gè)都是有效狀態(tài)
SIGNAL: -1,等待被喚醒
CONDITION:-2,等待被條件變量喚醒
PROPAGATE:-3,沒看懂....

只有 ConditionObject 中 waitStatus 才可能是 CONDITION

  1. 條件變量類
    public class ConditionObject implements Condition, java.io.Serializable {
        /** First node of condition queue. */
        private transient Node firstWaiter;
        /** Last node of condition queue. */
        private transient Node lastWaiter;

條件變量實(shí)際也是一個(gè) Node 組成的鏈表,這里沒有啞元,都是有效節(jié)點(diǎn),而且這個(gè)鏈表是單向的,因?yàn)樗玫氖莕extWaiter屬性。

1.3 加鎖、解鎖方法沒有具體實(shí)現(xiàn)

對(duì)于加鎖、解鎖方法,AQS 并沒有具體實(shí)現(xiàn),而是留給子類去實(shí)現(xiàn)。

2. 加鎖、就鎖過程

因?yàn)?AQS 是抽象類,加鎖、解鎖的方法沒有具體實(shí)現(xiàn),而是留給子類去實(shí)現(xiàn),所以這里只是說一下大概思想和流程。

加鎖成功
通過對(duì) state 屬性 CAS 嘗試將其從 0 改為 1,如果修改成功,就進(jìn)一步把 exclusiveOwnerThread 設(shè)置為當(dāng)前線程。這樣就加鎖成功了。

鎖重入
CAS 修改 state 的時(shí)候失敗的話,會(huì)先判斷 exclusiveOwnerThread == Thread.currentThread() 是否為真,如果是真,就說明是鎖重入,state++ 即可。

加鎖失敗
和 monitor 類似,如果加鎖失敗而且不是鎖重入的情況,就需要讓線程進(jìn)入阻塞隊(duì)列,將線程封裝在 Node 對(duì)象中,添加到隊(duì)尾。

解鎖
解鎖,就是每釋放一次鎖,就 state--,減到 0,說明已經(jīng)是最初加鎖的地方了,將 exclusiveOwnerThread 設(shè)置為 null。

AQS 只是給出抽象的框架,具體是公平還是非公平,共享還是排他等等一些細(xì)節(jié)仍需要子類去具體實(shí)現(xiàn)。

AQS 對(duì)屬性的 CAS 操作都有實(shí)現(xiàn),基于 Unsafe,阻塞、喚醒線程用的是 LockSupport.park(t), LockSupport.unPark(),實(shí)際上也是 基于Unsafe 類

3. 條件變量

3.1 await 阻塞

        public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }

addConditionWaiter 方法就是將阻塞線程用 Node 封裝一下,加到隊(duì)尾。

        private Node addConditionWaiter() {
            Node t = lastWaiter;
            // If lastWaiter is cancelled, clean out.
            if (t != null && t.waitStatus != Node.CONDITION) {
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
            if (t == null)
                firstWaiter = node;
            else
                t.nextWaiter = node;
            lastWaiter = node;
            return node;
        }

添加到條件變量隊(duì)尾之后,因?yàn)榫€程還未阻塞,有可能在此過程中獲取到了鎖,然而開發(fā)者調(diào)用 await 是為了阻塞線程,并等待 signal 喚醒,并不希望它此時(shí)得到鎖,所以調(diào)用 fullyRelease 將鎖釋放(如果得到了鎖)。

    final int fullyRelease(Node node) {
        boolean failed = true;
        try {
            int savedState = getState();
            if (release(savedState)) {
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)
                node.waitStatus = Node.CANCELLED;
        }
    }

當(dāng)前節(jié)點(diǎn)已經(jīng)加入到 ConditionObject 的單向隊(duì)列中,但是是否加到了 AQS 阻塞隊(duì)列需要用 isOnSyncQueue 方法來判斷。

    final boolean isOnSyncQueue(Node node) {
        if (node.waitStatus == Node.CONDITION || node.prev == null)
            return false;
        if (node.next != null) // If has successor, it must be on queue
            return true;
        /*
         * node.prev can be non-null, but not yet on queue because
         * the CAS to place it on queue can fail. So we have to
         * traverse from tail to make sure it actually made it.  It
         * will always be near the tail in calls to this method, and
         * unless the CAS failed (which is unlikely), it will be
         * there, so we hardly ever traverse much.
         */
        return findNodeFromTail(node);
    }

如果還沒有被添加到 AQS 隊(duì)列中,就將線程 park。如果能從 while (!isOnSyncQueue(node)) 循環(huán)中出來,說明被加載到了 AQS 阻塞隊(duì)列中了,或者是 park 被喚醒了。

3.2 signal 喚醒

如果線程持有鎖,那 signal 方法會(huì)報(bào)錯(cuò),否則就喚醒隊(duì)列中的第一個(gè)節(jié)點(diǎn)。

        public final void signal() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignal(first);
        }
        private void doSignal(Node first) {
            do {
                //將頭結(jié)點(diǎn)更換為頭結(jié)點(diǎn)的后繼節(jié)點(diǎn)
                if ( (firstWaiter = first.nextWaiter) == null)
                    lastWaiter = null;
                first.nextWaiter = null;
            } while (!transferForSignal(first) &&
                     (first = firstWaiter) != null);
        }

嘗試釋放

    final boolean transferForSignal(Node node) {
        /*
         * If cannot change waitStatus, the node has been cancelled.
         */
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;

        /*
         * 將從條將變量取出的頭結(jié)點(diǎn),添加到 AQS 的尾結(jié)點(diǎn)中
         */
        Node p = enq(node);
        int ws = p.waitStatus;
        // 判斷 waitStatus,如果大于零或者,修改為 SIGNAL 失敗,就 unpark 該節(jié)點(diǎn)退出阻塞
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    }

線程是阻塞在上面的 await 方法中,在 transferForSignal 將線程 unpark 之后,就會(huì)執(zhí)行 await 后面的代碼,大致就是清除節(jié)點(diǎn)之類的。之后就可以正常實(shí)行業(yè)務(wù)邏輯了。

還有一種情況,修改沒有進(jìn)入到 unpark 的邏輯之中,這種的就要排隊(duì)等著了。。。等它的前驅(qū)節(jié)點(diǎn)喚醒它。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容