Android消息處理機(jī)制之Message是如何重復(fù)利用的?

  • 問題的引出

我們知道Android開發(fā)中我們是一般不會(huì)在子線程中去更新UI,而是利用Handler將當(dāng)前子線程的消息post(Runnable)到主線程中去,這樣就可以安全的更新UI了,看過Handler源碼的同學(xué)應(yīng)該知道post(Runnable
)底層就是將Runnable轉(zhuǎn)化為Message然后交給Handler去處理的。這時(shí)我們發(fā)現(xiàn)一個(gè)問題,那就是在android中大量的UI更新是不是會(huì)創(chuàng)建大量的Message呢?

  • 探究android是如何去處理處理大量的Message

看看Message源碼類注釋,從下面的注釋可以知道,它推薦我們通過Message.obtain()的方式去獲取一個(gè)Message使用,還有我們看到一個(gè)關(guān)鍵字"recycled",說明通過這個(gè)方法獲取的Message是從回收池pool中獲取的。

/**
 * 
 * Defines a message containing a description and arbitrary data object that can be
 * sent to a {@link Handler}.  This object contains two extra int fields and an
 * extra object field that allow you to not do allocations in many cases.  
 *
 * <p class="note">While the constructor of Message is public, the best way to get
 * one of these is to call {@link #obtain Message.obtain()} or one of the
 * {@link Handler#obtainMessagerecycleUnchecked Handler.obtainMessage()} methods, which will pull
 * them from a pool of recycled objects.</p>
 */

  • 關(guān)注怎么怎么從回收池中獲取Message的

在首次調(diào)用obtain方法時(shí),①當(dāng)前pool中沒有Message可用,因此會(huì)創(chuàng)建一個(gè)Message對(duì)象②當(dāng)前pool有Message可用則直接取出表頭Message。現(xiàn)在我發(fā)現(xiàn)一個(gè)問題,那就是創(chuàng)建了一個(gè)Message對(duì)象之后,它是什么時(shí)候添加到pool中的?

  • next:是Message的屬性,是Message類型的,指向的是下一個(gè)Messae對(duì)象,因此從這點(diǎn)可以看出,它是一個(gè)鏈表的方式實(shí)現(xiàn)的。
  • sPoolSync:一個(gè)普通的object,純粹是為了同步鎖使用
  • sPool:表頭
public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

public Message() {
}
  • 探索Message是怎么被存到鏈表中的?

首先我們要Handler的工作需要誰來配合?很簡(jiǎn)單,那就是Message,MessageQueue和Looper。下面我簡(jiǎn)單的說說每一個(gè)類的作用,詳細(xì)請(qǐng)參考另一篇博客[Handler消息處理機(jī)制][1]
[1]:http://blog.csdn.net/lwj_zeal/article/details/52814068 "Handler消息處理機(jī)制"

  • Message:Handler處理的消息。
  • MessageQueue:消息隊(duì)列,專門負(fù)責(zé)存儲(chǔ)消息的。
  • Looper:消息輪訓(xùn)器,輪訓(xùn)消息隊(duì)列獲取消息交給Handler去處理。

知道了上面的關(guān)系之后,那么我們得找到切入點(diǎn),我們知道Looper是負(fù)責(zé)輪訓(xùn)消息隊(duì)列的,然后取出消息交給Handler去處理,那么我們就可以猜測(cè)它既然可以取消息,那么肯定需要解決handler處理的Message的,追蹤源碼Looper.loop()瞅瞅:

public static void loop() {
    final Looper me = myLooper();
    ...
    for (;;) {//阻塞
        //取出一個(gè)消息
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        ...
        try {
            //讓handler去處理這個(gè)消息
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        //handler處理完消息之后,回收消息
        //關(guān)鍵代碼
        msg.recycleUnchecked();
    }
}

Message:recycleUnchecked
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) {
        //當(dāng)前pool中的Message還沒有超過MAX_POOL_SIZE時(shí)
        //將將消息添加到鏈表中,這里就實(shí)現(xiàn)了pool添加Message的操作了
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}
  • 結(jié)論

從Message類的源碼注釋中也可以看出,它推薦通過Message.obtain()方法獲取一個(gè)Message對(duì)象,這個(gè)可以減少內(nèi)存的消耗,也是比較規(guī)范的寫法。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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