Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 的 Message Pool 究竟是什麼——源碼角度深度剖析

編輯:關於 Android 開發

Android 的 Message Pool 究竟是什麼——源碼角度深度剖析

原文地址:https://blog.csdn.net/xplee0576/article/details/46875555

在 Android 中,我們在線程之間通信時通常采用消息機制,而這一機制所傳遞的正是 Message 對象。日常開發中,我們習慣使用 Message.obtain() 與 Handler.obtainMessage() 從 Message Pool 中獲取 Message,以避免直接構造 Message 對象。

那麼,Android 是否會因為 Message Pool 緩存的 Message 對象而導致 OOM 呢?對此可以明確回答:App 不會因 Message Pool 而 OOM。至於原因,不妨一步步往下看,心急的朋友也可以直接跳到最後一節——Message Pool 如何存放 Message。

Message Obtain 分析

Message.obtain() 源碼

/**
 * 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 m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

從這段程式碼可以看到,Message 是由 sPool 直接賦值取得的,只有當池已空時才會 new 一個新對象。

Handler.obtainMessage() 源碼

/**
 * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
 * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
 * If you don't want that facility, just call Message.obtain() instead.
 */
public final Message obtainMessage() {
    return Message.obtain(this);
}

可見 Handler.obtainMessage() 最終仍是調用 Message.obtain() 來獲取的。

Message Pool 相關源碼分析

Message Pool 的數據結構

// sometimes we store linked lists of these things
/*package*/ Message next;

private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
private static boolean gCheckRecycle = true;

從程式碼可以清楚地看到,Message Pool 的數據結構實際上就是一個鏈表。sPool 是全局的消息池頭節點,sPoolSize 記錄鏈表長度,而 MAX_POOL_SIZE 則規定鏈表的最大長度為 50。

Message Pool 如何存放 Message

/** @hide */
public static void updateCheckRecycle(int targetSdkVersion) {
    if (targetSdkVersion < Build.VERSION_CODES.LOLLIPOP) {
        gCheckRecycle = false;
    }
}

/**
 * Return a Message instance to the global pool.
 * You MUST NOT touch the Message after calling this function.
 */
public void recycle() {
    if (isInUse()) {
        if (gCheckRecycle) {
            throw new IllegalStateException("This message cannot be recycled because it "
                    + "is still in use.");
        }
        return;
    }
    recycleUnchecked();
}

void recycleUnchecked() {
    // Mark the message as in use while it remains in the recycled object pool.
    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(),其關鍵邏輯可分為兩步:

1、清空字段:將待回收的 Message 對象字段逐一置空(obj、data、callback 等),以避免因 Message 體積過大而使靜態的消息池造成記憶體洩漏。因此,無論原先的 Message 對象有多大,在被緩存進 Message Pool 之前都會被置空,這些緩存對象所佔的記憶體對整個 App 而言幾乎可以忽略。這也正是 Message Pool 不會導致 OOM 的根本原因。

2、線程安全地入池:以內置鎖(synchronized)的方式判斷當前池大小是否小於 50。若小於 50,則將該 Message 頭插到消息池鏈表;若已達到或超過 50,則直接丟棄,這些被丟棄的 Message 將交由 GC 回收處理。

由此可見,Message Pool 通過「有限緩存 + 對象複用 + 字段清空」的設計,在提升性能的同時有效規避了記憶體洩漏風險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved