03_Condition_2_實現類

一:類ConditionObject,基礎操作和內部結構

public class ConditionObject implements Condition, java.io.Serializable {
    private static final long serialVersionUID = 1173984872572414699L;
    /** First node of condition queue. 
     * 這里也是用的AQS中的Node,這里只是用到Node中的nextWaiter,不是pre和next,所以是一個單項鏈表。
     * */
    private transient Node firstWaiter;
    /** Last node of condition queue. */
    private transient Node lastWaiter;

    /**
     * Creates a new {@code ConditionObject} instance.
     */
    public ConditionObject() { }

    /**
     * Adds a new waiter to wait queue.
     * 往等待隊列中添加一個新的等待者。
     * @return its new wait node
     */
    private Node addConditionWaiter() {
        Node t = lastWaiter;
        // If lastWaiter is cancelled, clean out. 如果最后一個等待著已經被取消,則清除掉。
        if (t != null && t.waitStatus != Node.CONDITION) {
            unlinkCancelledWaiters();
            t = lastWaiter;
        }
        //這里就將waitStatus中的CONDITION狀態給用到了。
       // Node.CONDITION的注釋中有說明,該狀態表示節點在條件隊列中。
        Node node = new Node(Thread.currentThread(), Node.CONDITION);
        if (t == null)
            firstWaiter = node;
        else
            t.nextWaiter = node;
        lastWaiter = node;
        return node;
    }

    /**
     * Unlinks cancelled waiter nodes from condition queue.
     * Called only while holding lock. This is called when
     * cancellation occurred during condition wait, and upon
     * insertion of a new waiter when lastWaiter is seen to have
     * been cancelled. This method is needed to avoid garbage
     * retention in the absence of signals. So even though it may
     * require a full traversal, it comes into play only when
     * timeouts or cancellations occur in the absence of
     * signals. It traverses all nodes rather than stopping at a
     * particular target to unlink all pointers to garbage nodes
     * without requiring many re-traversals during cancellation
     * storms.
     * 從條件隊列中將已取消的等待節點移除(取消鏈接)。只有在持有鎖的時候調用。
     * 當在條件等待期間發生取消時,以及在插入新的等待者期間發現lastWaiter是已取消的時候,調用此函數。
     * 需要這種方法來避免在沒有信號的情況下垃圾保留。
     * 因此,即使它可能需要一個完整的遍歷,它也只有在沒有信號的情況下發生超時或取消才會起作用。
     * 它遍歷所有節點,而不是在特定目標處停止,以取消所有指向垃圾節點的指針的鏈接,而無需在取消風暴期間多次重新遍歷。
     * 就是從頭到位遍歷,將所有取消的節點剔除。
     */
    private void unlinkCancelledWaiters() {
        Node t = firstWaiter;
        Node trail = null;
        while (t != null) {
            Node next = t.nextWaiter;
            if (t.waitStatus != Node.CONDITION) {
                t.nextWaiter = null;
                if (trail == null)
                    firstWaiter = next;
                else
                    trail.nextWaiter = next;
                if (next == null)
                    lastWaiter = trail;
            }
            else
                trail = t;
            t = next;
        }
    }
}

總結:

  1. 此類中也是使用Node來維護了一個單向鏈表,維護所有等待該Condition的線程隊列,和AQS中的同步隊列不是一個隊列,
    這兩個隊列是會交互的。
  2. 此類中的Node的waitStatus都是Condition,表示等待狀態,表示該節點處于等待隊列中。
  3. 兩個基本的操作,添加新節點和刪除取消的節點。

二:await邏輯

public class ConditionObject implements Condition, java.io.Serializable {
    /**
     * Implements interruptible condition wait.
     * 實現可中斷的條件等待。(下面的注釋已經大體描述清楚每一步的邏輯了)
     * <ol>
     * <li> If current thread is interrupted, throw InterruptedException.
     *      如果當前線程已經被中斷,則拋出InterruptedException。
     *      
     * <li> Save lock state returned by {@link #getState}.
     *      getState方法返回保存的鎖狀態。
     *      
     * <li> Invoke {@link #release} with saved state as argument,
     *      throwing IllegalMonitorStateException if it fails.
     *      通過保存狀態作為參數來調用release方法,如果失敗則拋出IllegalMonitorStateException。
     *      
     * <li> Block until signalled or interrupted.
     *      阻塞至被信號通知或被中斷。
     *      
     * <li> Reacquire by invoking specialized version of
     *      {@link #acquire} with saved state as argument.
     *      通過調用acquire的專用版本并將保存的狀態作為參數來重新獲取
     *      
     * <li> If interrupted while blocked in step 4, throw InterruptedException.
     *      如果在步驟4中阻塞時被中斷,則拋出InterruptedException。
     * </ol>
     */
    public final void await() throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        Node node = addConditionWaiter(); //創建一個condition類型的Node并入鏈
        int savedState = fullyRelease(node);//完全釋放并返回當時的state
        int interruptMode = 0;
        //判斷是否在AQS的同步隊列中,不在表示還未signal,在了表示已經被signal了
        while (!isOnSyncQueue(node)) {
            //1. fullyRelease后node不在AQS的同步隊列中了,所以會立即進入該方法,后續該線程被park
            //其他線程調用signal時會將此線程unpark,又會將此線程添加到AQS的同步隊列中去,結束wile循環。后面在看signal。
            //2. 會不會此時已經在AQS的同步隊列中了呢,應該也是會的,就是此線程剛fullyRelease,
            // 其它線程signal的時候又將該node給加到了同步隊列中,此時就不park了,直接往后執行就可以了。
            //3. 如果park之前被中斷了,那么此處的park會不起作用,直接往下繼續執行。
            LockSupport.park(this);
            if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                //阻塞的過程中被中斷了,就直接break出來
                //checkInterruptWhileWaiting用來檢測中斷的時機并將node加到AQS隊列中,后面再細看。
                break;
        }
        if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
            //acquireQueued需要再次獲取鎖資源
            // 這里會存在獲取不到鎖資源的情況嗎?不會,即使上面不是因為signal喚醒而unpark,而是因為中斷而喚醒,從而執行到這里,
            // acquireQueued也必須獲取到鎖,獲取不要會繼續給park住,然后排隊等待獲取,
            // 而且acquireQueued方法是不支持中斷的,只能等到獲取成功才會繼續執行。而且await之前執行了lock操作,之后還會執行unlock操作,
            //如果說獲取不到那不就出錯了嘛。
            interruptMode = REINTERRUPT;
        if (node.nextWaiter != null) // clean up if cancelled 清理被取消的節點
            unlinkCancelledWaiters();
        if (interruptMode != 0)
            reportInterruptAfterWait(interruptMode);//將中斷狀態給報告出去
    }

    /**
     * Invokes release with current state value; returns saved state.
     * Cancels node and throws exception on failure.
     * 使用當前state值調用release;返回保存的state。失敗時取消節點并拋出異常。
     * 
     * @param node the condition node for this wait
     * @return previous sync state
     */
    final int fullyRelease(Node node) {
        boolean failed = true;
        try {
            int savedState = getState();
            //為什么不是release(1)呢?因為如果是可重入的,比如說thread1鎖了2次,這個saveState為2,
            //release(1)不會完全釋放當前鎖,所以這個方法叫做fullyRelease,完全釋放。
            //為什么又要返回這個savedState呢? thread1鎖了2次,await的時候會通過該方法釋放掉,其它線程會再次獲得鎖,
            //那么等thread1被signal時,會重新acquire(savedState)獲取鎖,并將state的設置到正確狀態,
            // thread1 lock了兩次,肯定會unlock兩次,如果state為1,第二次unlock時就會報錯。
            if (release(savedState)) {
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)
                node.waitStatus = Node.CANCELLED;
        }
    }

    /** Mode meaning to reinterrupt on exit from wait */
    //該模式意味著退出等待時重新中斷,發出信號后被中斷
    private static final int REINTERRUPT =  1;
    /** Mode meaning to throw InterruptedException on exit from wait */
    //模式意味著退出等待時拋出InterruptedException,發出信號前被中斷
    private static final int THROW_IE    = -1;
    
    /**
     * Checks for interrupt, returning THROW_IE if interrupted
     * before signalled, REINTERRUPT if after signalled, or
     * 0 if not interrupted.
     * 檢查中斷,
     *  如果在發出信號前被中斷,則返回THROW_IE,
     *  發出信號后被中斷則返回REINTERRUPT,
     *  沒有被中斷則返回0.
     */
    private int checkInterruptWhileWaiting(Node node) {
        return Thread.interrupted() ?
                (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
                0;
    }

    /**
     * Transfers node, if necessary, to sync queue after a cancelled wait.
     * Returns true if thread was cancelled before being signalled.
     * 如有必要,在取消等待后將節點傳輸到同步隊列。如果線程在發出信號之前被取消,則返回true。
     *
     * @param node the node
     * @return true if cancelled before the node was signalled
     */
    final boolean transferAfterCancelledWait(Node node) {
        if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
            //場景:一個線程在await,其它線程一直沒有對其進行signal,然后該線程又被interrupt了。
            // await進行park前,已經將鎖給釋放掉了,中斷后會從park中醒過來繼續acquireQueued獲取鎖,
            //acquireQueued操作的是同步隊列中的node,所以需要將node加到AQS的同步隊列中去。
            enq(node);
            return true;
        }
        /*
         * If we lost out to a signal(), then we can't proceed
         * until it finishes its enq().  Cancelling during an
         * incomplete transfer is both rare and transient, so just
         * spin.
         * 如果我們輸給了一個signal(),直到它完成enq()否則我們無法繼續。
         * 在不完全傳輸過程中的取消既罕見又短暫,所以只需旋轉即可。
         * 
         * 啥意思呢? signal的第一步就會將node的狀態從CONDITION改為0,那么該方法上面的CAS操作將會失敗,
         * 出現的原因是因為interrupt和signal方法幾乎同時執行,但是signal的CAS操作比此方法的CAS操作快了一步。
         */
        while (!isOnSyncQueue(node))
            // 循環一下等待node在signal中被enq到同步隊列中去。
            Thread.yield();
        return false;
    }

    /**
     * Throws InterruptedException, reinterrupts current thread, or
     * does nothing, depending on mode.
     * 基于mode 來拋出InterruptedException、重新中斷當前線程或者啥都不做。
     */
    private void reportInterruptAfterWait(int interruptMode)
            throws InterruptedException {
        if (interruptMode == THROW_IE)
            throw new InterruptedException();
        else if (interruptMode == REINTERRUPT)
            selfInterrupt();
    }
}

總結:

  1. 正常的等待邏輯比較直觀,分為以下幾步(一個線程await,一個線程signal):

    • 1.0 lock()獲取鎖、await()等待。
    • 1.1 addConditionWaiter創建一個Condition狀態的節點并加入到隊列。
    • 1.2 fullyRelease 將鎖釋放,并保存好AQS中的狀態(savedState)。
    • 1.3 park線程,等待其它線程signal通知。
    • 1.4 其它線程調用signal,以及unlock,等待線程從park中喚醒
    • 1.5 acquireQueued 重新獲取鎖,并將1.2中的savedState狀態從新設置到AQS的state字段。
    • 1.6 執行業務邏輯,最后釋放鎖 unlock()。
  2. 中斷發生,并且發生在signal之前(一個線程await,一個線程signal):

    • 2.1 發生在park之前,那么park不起作用,直接往后執行。
    • 2.2 發生在park之后,線程從park中喚醒。
    • 2.3 transferAfterCancelledWait 將node的狀態成功的從CONDITION改為0,并且將node添加到AQS的同步隊列。
    • 2.4 上一步可能將node的狀態從CONDITION改為0失敗,表示signal已經發生了,這時算作中斷發生在signal之后。
    • 2.5 acquireQueued 重新獲取鎖,并將savedState狀態重新設置到AQS的state字段。
    • 2.6 reportInterruptAfterWait 將拋出InterruptedException。
  3. 中斷發生,并且發生在signal之后

    • 3.1 其它線程調用signal,以及unlock,等待線程從park中喚醒
    • 3.2 acquireQueued 重新獲取鎖,并將savedState狀態重新設置到AQS的state字段。
    • 3.3 reportInterruptAfterWait 將重新執行Thread.interrupt().
  4. 多個線程await,被多次signal,每次signal則喚醒一個await的線程。

  5. 多個線程await,被signalAll同時喚醒,其實應該說是將等待隊列中的線程逐個喚醒。

三:signal邏輯

public class ConditionObject implements Condition, java.io.Serializable {
    /**
     * Moves the longest-waiting thread, if one exists, from the
     * wait queue for this condition to the wait queue for the
     * owning lock.
     * 將等待時間最長的線程(如果存在)從該條件的等待隊列移動到擁有鎖的等待隊列。
     * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
     *         returns {@code false}
     */
    public final void signal() {
        if (!isHeldExclusively())
            //如果不是當前線程獲得的鎖,則拋出異常
            throw new IllegalMonitorStateException();
        Node first = firstWaiter;//firstWaiter表示等待時間最長的節點。
        if (first != null)
            doSignal(first);
    }

    /**
     * Removes and transfers nodes until hit non-cancelled one or
     * null. Split out from signal in part to encourage compilers
     * to inline the case of no waiters.
     * 刪除和傳輸節點,直到命中未取消的一個node或null。
     * 從signal中分離出來,部分是為了鼓勵編譯器在沒有等待者的情況下inline。
     * @param first (non-null) the first node on condition queue
     */
    private void doSignal(Node first) {
        do {
            //將first的下個節點作為新的first
            if ( (firstWaiter = first.nextWaiter) == null)
                lastWaiter = null;
            first.nextWaiter = null;
        } while (!transferForSignal(first) &&
                (first = firstWaiter) != null);//如果轉換失敗,繼續循環,繼續轉換下一個節點
    }

    /**
     * Transfers a node from a condition queue onto sync queue.
     * Returns true if successful.
     * 將節點從等待隊列傳輸到同步隊列。成功則返回true。
     * @param node the node
     * @return true if successfully transferred (else the node was
     * cancelled before signal)
     */
    final boolean transferForSignal(Node node) {
        /*
         * If cannot change waitStatus, the node has been cancelled.
         * 如果不能改變waitStatus,則該node已經被取消了。
         * 因為await的時候,如果發生interrupt,則會將此狀態設置為0,表示已經取消等待。
         */
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;

        /*
         * Splice onto queue and try to set waitStatus of predecessor to
         * indicate that thread is (probably) waiting. If cancelled or
         * attempt to set waitStatus fails, wake up to resync (in which
         * case the waitStatus can be transiently and harmlessly wrong).
         * 拼接到隊列上,并嘗試設置前置線程的waitStatus,以指示線程(可能)正在等待。
         * 如果已取消或嘗試設置waitStatus失敗,則喚醒以重新同步(在這種情況下,waitStatus可能會暫時錯誤,且不會造成傷害)
         * 通過AQS的enq方法將節點傳輸到AQS的同步隊列上
         */
        Node p = enq(node);
        int ws = p.waitStatus;
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            //被取消了或者狀態修改失敗,直接unpark
            LockSupport.unpark(node.thread);
        return true;
    }

   /**
    * Moves all threads from the wait queue for this condition to
    * the wait queue for the owning lock.
    * 將此條件的所有線程從等待隊列移動到擁有鎖的等待隊列。
    */
   public final void signalAll() {
      if (!isHeldExclusively())
         throw new IllegalMonitorStateException();
      Node first = firstWaiter;
      if (first != null)
         doSignalAll(first);
   }

   /**
    * Removes and transfers all nodes.
    * @param first (non-null) the first node on condition queue
    */
   private void doSignalAll(Node first) {
      lastWaiter = firstWaiter = null;
      do {
          //循環所有的等待節點,依次transferForSignal
         Node next = first.nextWaiter;
         first.nextWaiter = null;
         transferForSignal(first);
         first = next;
      } while (first != null);
   }
}

總結:

  1. signal 單個喚醒,則將第一個節點firstWaiter狀態從CONDITION改為0,并加等待隊列轉移到同步隊列中。
  2. signalAll 則是從第一個循環到最后一個,都處理一遍。
  3. 這里的signal并不會直接將等待節點的線程unpark,而是加到了同步隊列,等通知者線程unlock了,release邏輯會將等待線程unpark。
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容