Android開發Message原始碼分析【享元模式|物件池】

王世暉發表於2016-05-19

享元模式介紹

享元模式是物件池的一種實現,儘可能減少記憶體的使用,使用快取來共享可用的物件,避免建立過多的物件。Android中Message使用的設計模式就是享元模式,獲取Message通過obtain方法從物件池獲取,Message使用結束通過recycle將Message歸還給物件池,達到迴圈利用物件,避免重複建立的目的

Message原始碼分析

Message中有關於物件池的屬性如下:

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

採用連結串列的形式達到物件池的功能,next為指向物件池下一個物件的指標,sPool始終指向連結串列隊首,sPoolSize表示當前連結串列資料量,MAX_POOL_SIZE表示物件池容量,sPoolSync專門用來給物件池上鎖,達到互斥訪問的目的。
注意命名規則,static變數以小寫字母s開頭,static final 為常量,全部大寫

使用obtain從物件池獲取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 m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

物件池屬於臨界區,訪問需要加鎖,這裡並沒有使用synchronized修飾obtain方法,是為了減小鎖的粒度。
可見obtain方法首先判斷物件池是否為空,空的話直接通過構造方法建立一個新的Message物件返回。不空的話從連結串列頭部取出一個Message物件,連結串列頭指標指向下一個物件,將該Message物件next指標域置空,標誌位置空,物件池物件數量大小減一,返回這個Message物件

使用recycle方法回收Message物件

    /**
     * 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();
    }

recycle方法回收的物件必須是可回收的,即已經不再使用的,否則的話丟擲異常。

 /**
     * 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++;
            }
        }
    }

回收方法是把Message物件的所有標誌位清空,資料清空,然後將此回收的Message物件加入到連結串列的頭部,這樣一個廢棄的Message物件就被回收了。

相關文章