Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android的Message Pool是什麼——源碼角度分析,androidpool

Android的Message Pool是什麼——源碼角度分析,androidpool

編輯:關於android開發

Android的Message Pool是什麼——源碼角度分析,androidpool


原文地址:

      http://blog.csdn.net/xplee0576/article/details/46875555

 

Android中,我們在線程之間通信傳遞通常采用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賦值的。

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.obtain()最終還是調用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.
     * <p>
     * You MUST NOT touch the Message after calling this function because it has
     * effectively been freed.  It is an error to recycle a message that is currently
     * enqueued or that is in the process of being delivered to a Handler.
     * </p>
     */
    public void recycle() {
        if (isInUse()) {
            if (gCheckRecycle) {
                throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
            }
            return;
        }
        recycleUnchecked();
    }

    /**
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     */
    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()方法:

1、將待回收的Message對象字段置空(避免因Message過大,使靜態的消息池內存洩漏)。因此無論原先的Message對象有多大,最終被緩存進Message Pool前都被置空,那麼這些緩存的Message對象所占內存大小對於一個app內存來說基本可以忽略。所以說,Message Pool並不會造成App的OOM。

2、以內置鎖的方式(線程安全),判斷當前線程池的大小是否小於50。若小於50,直接將Mesaage插入到消息池鏈表尾部;若大於等於50,則直接丟棄掉,那麼這些被丟棄的Message將交由GC處理。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved