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

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

根據(jù)官方文檔:

Looper.quit()

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

Looper.quitsafely()

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

Looper

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
public static void loop() {
   ...
    for (;;) {
        // 獲取消息隊(duì)列中的下一個(gè)消息,如果消息隊(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);
        }
        // 最后回收這個(gè) 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)就會(huì)結(jié)束
    mMessages = null;
}

private void removeAllFutureMessagesLocked() {
    final long now = SystemClock.uptimeMillis();
    Message p = mMessages;
    if (p != null) {
        //如果表頭的消息是延遲消息锋喜,那么整個(gè)消息隊(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ī)制就啟動(dòng)了,根據(jù)上面的代碼可以看到loop()里面有一個(gè)for循環(huán)涯冠,只有當(dāng)MessageQueuenext()返回null的時(shí)候才會(huì)退出循環(huán)終止Handler機(jī)制炉奴。再看看MessageQueuenext()我們也看到一個(gè)for循環(huán),如果有消息的話就把消息返回蛇更,沒有消息且mQuitting=false的時(shí)候繼續(xù)循環(huán)下去瞻赶,只有當(dāng)沒有消息然后mQuitting=true的時(shí)候返回null

根據(jù)Looper代碼所示Looper.quit()最終會(huì)調(diào)用MessageQueue.removeAllMessagesLocked()派任,而Looper.quitsafely()會(huì)調(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í)設(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緩存池也是一個(gè)鏈表奠滑,沒有的話就通過把Message以頭部添加方式放到緩存池中。

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

官方推薦需要?jiǎng)?chuàng)建Message對(duì)象的時(shí)候通過Message.obtain()來獲取。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末养叛,一起剝皮案震驚了整個(gè)濱河市种呐,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌弃甥,老刑警劉巖爽室,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異淆攻,居然都是意外死亡阔墩,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門瓶珊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來啸箫,“玉大人,你說我怎么就攤上這事伞芹⊥粒” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵唱较,是天一觀的道長(zhǎng)扎唾。 經(jīng)常有香客問我,道長(zhǎng)南缓,這世上最難降的妖魔是什么胸遇? 我笑而不...
    開封第一講書人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮汉形,結(jié)果婚禮上纸镊,老公的妹妹穿的比我還像新娘。我一直安慰自己概疆,他們只是感情好逗威,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著届案,像睡著了一般庵楷。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上楣颠,一...
    開封第一講書人閱讀 51,462評(píng)論 1 302
  • 那天尽纽,我揣著相機(jī)與錄音,去河邊找鬼童漩。 笑死弄贿,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的矫膨。 我是一名探鬼主播差凹,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼期奔,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了危尿?” 一聲冷哼從身側(cè)響起呐萌,我...
    開封第一講書人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎谊娇,沒想到半個(gè)月后肺孤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡济欢,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年赠堵,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片法褥。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡茫叭,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出半等,到底是詐尸還是另有隱情揍愁,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布杀饵,位于F島的核電站吗垮,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏凹髓。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一怯屉、第九天 我趴在偏房一處隱蔽的房頂上張望蔚舀。 院中可真熱鬧,春花似錦锨络、人聲如沸赌躺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽礼患。三九已至,卻和暖如春掠归,著一層夾襖步出監(jiān)牢的瞬間缅叠,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來泰國打工虏冻, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留肤粱,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓厨相,卻偏偏與公主長(zhǎng)得像领曼,于是被迫代替她去往敵國和親鸥鹉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容