Handler機(jī)制之Looper.quit()和Looper.quitsafely()

調(diào)用Looper.quit()和Looper.quitsafely()的時候發(fā)生了什么?

根據(jù)官方文檔:

Looper.quit()

調(diào)用后直接終止Looper,不在處理任何Message,所有嘗試把Message放進(jìn)消息隊(duì)列的操作都會失敗,比如Handler.sendMessage()會返回 false,但是存在不安全性,因?yàn)橛锌赡苡?code>Message還在消息隊(duì)列中沒來的及處理就終止Looper了。

Looper.quitsafely()

調(diào)用后會在所有消息都處理后再終止Looper,所有嘗試把Message放進(jìn)消息隊(duì)列的操作也都會失敗。

Looper

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
public static void loop() {
   ...
    for (;;) {
        // 獲取消息隊(duì)列中的下一個消息,如果消息隊(duì)列沒有消息就阻塞
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        // This must be in a local variable, in case a UI event sets the logger
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }

        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }

        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed from 0x"
                    + Long.toHexString(ident) + " to 0x"
                    + Long.toHexString(newIdent) + " while dispatching to "
                    + msg.target.getClass().getName() + " "
                    + msg.callback + " what=" + msg.what);
        }
        // 最后回收這個 Message
        msg.recycleUnchecked();
    }
}
    
/**
 * Quits the looper.
 * <p>
 * Causes the {@link #loop} method to terminate without processing any
 * more messages in the message queue.
 * </p><p>
 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
 * For example, the {@link Handler#sendMessage(Message)} method will return false.
 * </p><p class="note">
 * Using this method may be unsafe because some messages may not be delivered
 * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
 * that all pending work is completed in an orderly manner.
 * </p>
 *
 * @see #quitSafely
 */
public void quit() {
    mQueue.quit(false);
}

/**
 * Quits the looper safely.
 * <p>
 * Causes the {@link #loop} method to terminate as soon as all remaining messages
 * in the message queue that are already due to be delivered have been handled.
 * However pending delayed messages with due times in the future will not be
 * delivered before the loop terminates.
 * </p><p>
 * Any attempt to post messages to the queue after the looper is asked to quit will fail.
 * For example, the {@link Handler#sendMessage(Message)} method will return false.
 * </p>
 */
public void quitSafely() {
    mQueue.quit(true);
}

都調(diào)用了MessageQueuequit(boolean)

MessageQueue

Message next() {
    ...
    synchronized (this) {
        // Try to retrieve the next message.  Return if found.
        final long now = SystemClock.uptimeMillis();
        Message prevMsg = null;
        Message msg = mMessages;
        if (msg != null && msg.target == null) {
            // Stalled by a barrier.  Find the next asynchronous message in the queue.
            do {
                prevMsg = msg;
                msg = msg.next;
            } while (msg != null && !msg.isAsynchronous());
        }
        if (msg != null) {
            if (now < msg.when) {
                // Next message is not ready.  Set a timeout to wake up when it is ready.
                nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
            } else {
                // Got a message.
                mBlocked = false;
                if (prevMsg != null) {
                    prevMsg.next = msg.next;
                } else {
                    mMessages = msg.next;
                }
                msg.next = null;
                if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                msg.markInUse();
                return msg;
            }
        } else {
            // No more messages.
            nextPollTimeoutMillis = -1;
        }
        if (mQuitting) {
            dispose();
            return null;
        }
        ...
    }
    ...     
}

void quit(boolean safe) {
    if (!mQuitAllowed) {
        throw new IllegalStateException("Main thread not allowed to quit.");
    }

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true; // 先把 mQuitting 改為 true

        if (safe) {
            removeAllFutureMessagesLocked();
        } else {
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}
    
private void removeAllMessagesLocked() {
    Message p = mMessages; // mMessages 是消息隊(duì)列單鏈表的表頭
    // 消息隊(duì)列所有消息都執(zhí)行 recycleUnchecked() 進(jìn)行回收
    while (p != null) { 
        Message n = p.next;
        p.recycleUnchecked();
     p = n;
    }
    // 最后把 mMessages 設(shè)置為 null Looper 的 for 循環(huán)就會結(jié)束
    mMessages = null;
}

private void removeAllFutureMessagesLocked() {
    final long now = SystemClock.uptimeMillis();
    Message p = mMessages;
    if (p != null) {
        //如果表頭的消息是延遲消息,那么整個消息隊(duì)列都可以直接回收了
        if (p.when > now) {
            removeAllMessagesLocked();
        } else {
            Message n;
            for (;;) {
                n = p.next;
                if (n == null) {
                    return;
                }
                // 如果當(dāng)前消息是延遲消息,跳出循環(huán)剩下消息進(jìn)入 do while 循環(huán)
                if (n.when > now) {
                    break;
                }
                p = n;
            }
            p.next = null;
            do {
                p = n;
                n = p.next;
                p.recycleUnchecked();
            } while (n != null);
        }
    }
}

在這里我們先回顧一下Message是怎么在Looper、MessageQueueHandler中傳遞了,我們知道當(dāng)Looper.loop()被執(zhí)行后Handler機(jī)制就啟動了,根據(jù)上面的代碼可以看到loop()里面有一個for循環(huán),只有當(dāng)MessageQueuenext()返回null的時候才會退出循環(huán)終止Handler機(jī)制。再看看MessageQueuenext()我們也看到一個for循環(huán),如果有消息的話就把消息返回,沒有消息且mQuitting=false的時候繼續(xù)循環(huán)下去,只有當(dāng)沒有消息然后mQuitting=true的時候返回null。

根據(jù)Looper代碼所示Looper.quit()最終會調(diào)用MessageQueue.removeAllMessagesLocked(),而Looper.quitsafely()會調(diào)用MessageQueue.removeAllFutureMessagesLocked()。

  • removeAllMessagesLocked() 表示直接把消息隊(duì)列里面的消息清空
  • removeAllFutureMessagesLocked() 表示把所有延遲消息清除

根據(jù)我在上面代碼中寫的注釋我們可以總結(jié)Looper.quit()Looper.quitsafely()做了什么和區(qū)別在哪里。

quit()實(shí)際上是把消息隊(duì)列全部清空,然后讓MessageQueue.next()返回null令Looper.loop()循環(huán)結(jié)束從而終止Handler機(jī)制,但是存在著不安全的地方是可能有些消息在消息隊(duì)列沒來得及處理。而quitsafely()做了優(yōu)化,只清除消息隊(duì)列中延遲信息,等待消息隊(duì)列剩余信息處理完之后再終止Looper循環(huán)。


所有Message被回收都需要調(diào)用Message.recycleUnchecked(),那么Message的回收機(jī)制是怎樣的呢,可以看看下面的代碼和注釋:

Message

/**
 * Return a new Message instance from the global pool. Allows us to
 * avoid allocating new objects in many cases.
 */
public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            // 從緩存池中獲取 Message
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            // 在這里把 recycleUnchecked() 中回收時設(shè)置的 in-use 標(biāo)志去掉
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

void recycleUnchecked() {
    // Mark the message as in use while it remains in the recycled object pool.
    // Clear out all other details.
    flags = FLAG_IN_USE;
    what = 0;
    arg1 = 0;
    arg2 = 0;
    obj = null;
    replyTo = null;
    sendingUid = -1;
    when = 0;
    target = null;
    callback = null;
    data = null;

    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

recycleUnchecked()回收Message過程分為兩步:

1 先把Message的變量初始化并標(biāo)記為 in-use 令該Message無法被發(fā)送到消息隊(duì)列。

2 判斷Message緩存池緩存數(shù)量是否達(dá)到上限(默認(rèn)50),Message緩存池也是一個鏈表,沒有的話就通過把Message以頭部添加方式放到緩存池中。

Message提供一個obtain()方法從緩存池中獲取回收的Message

官方推薦需要創(chuàng)建Message對象的時候通過Message.obtain()來獲取。

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

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

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