Handler的obtain享元模式

?我們使用消息時不要new出Message,要使用Message提供給我們的obtain方法。

Message msg = Message.obtain();
public final class Message implements Parcelable {
    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();
    }
}

使用一個消息后,消息池子相對應(yīng)會-1.

  public static void loop() {
        final Looper me = myLooper();
 ......
        for (;;) {
            Message msg = queue.next(); // might block
      ......
            msg.target.dispatchMessage(msg);
               
            msg.recycleUnchecked();
        }
    }

在調(diào)用完分發(fā)后,會執(zhí)行recycleUnchecked 回收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 = UID_NONE;
        workSourceUid = UID_NONE;
        when = 0;
        target = null;
        callback = null;
        data = null;
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

在recycleUnchecked中,會做一個置空的操作,然后sPool 會+1。

總結(jié):有一些變量可以反復(fù)使用,這個時候為了減少不必要的gc(),考慮使用享元模式。

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

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

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