1. 程式人生 > >android中使用物件池 ----- Pools

android中使用物件池 ----- Pools

最近在做音訊直播間的優化,發現Socket聊天部分,接收到的資訊,傳遞到adapter中時,總是new一個物件,再把資訊資料封裝進去傳遞給adapter。
這時候想這個new物件的動作其實是可以優化,試想直播間的聊天吹水是多麼頻繁,2000多號人在直播間聊天的時候,刷刷刷的滿屏滾動的聊天資訊,不停的new物件,給GC帶來的壓力可想而知。
所以搜了一下關於物件池方面的資料,記錄如下:

1、Apache Commons-pool2
一開始搜尋到這個common pool2框架,在Eclipse跑了下demo,發現還蠻不錯的,很多配置屬性,可控制;
可惜,移植到android上時,TMD不能用….因為pool2使用了JMX,而android虛擬機器中沒有jmx….大寫的尷尬!
不能用歸不能用了,筆記還是記下,也許哪天就可以用上了:

Apache Commons-pool2簡記

2.Pools
上面的common-pool2不能用後,又搜尋瞭解android方面的物件池資料,發現其實android自己就有pools工具類,在android.support.v4.util.Pools。
Pools原始碼很簡短:

/**
 * Helper class for creating pools of objects. An example use looks like this:
 * <pre>
 * public class MyPooledClass {//官方Pools使用demo
 *
 *     private static final SynchronizedPool<MyPooledClass> sPool =
 *             new SynchronizedPool<MyPooledClass>(10);
 *
 *     public static MyPooledClass obtain() {
 *         MyPooledClass instance = sPool.acquire();
 *         return (instance != null) ? instance : new MyPooledClass();
 *     }
 *
 *     public void recycle() {
 *          // Clear state if needed.
 *          sPool.release(this);
 *     }
 *
 *     . . .
 * }
 * </pre>
 *
 */
public final class Pools { /** * Interface for managing a pool of objects. * * @param <T> The pooled type. */ public static interface Pool<T> { /** * @return An instance from the pool if such, null otherwise. */ public T acquire();//獲取物件
/** * Release an instance to the pool. * * @param instance The instance to release. * @return Whether the instance was put in the pool. * * @throws IllegalStateException If the instance is already in the pool. */ public boolean release(T instance);//釋放物件 } private Pools() { /* do nothing - hiding constructor */ } /** * Simple (non-synchronized) pool of objects. * * @param <T> The pooled type. */ public static class SimplePool<T> implements Pool<T> { private final Object[] mPool; private int mPoolSize; /** * Creates a new instance. * * @param maxPoolSize The max pool size. * * @throws IllegalArgumentException If the max pool size is less than zero. */ public SimplePool(int maxPoolSize) { if (maxPoolSize <= 0) { throw new IllegalArgumentException("The max pool size must be > 0"); } mPool = new Object[maxPoolSize]; } @Override @SuppressWarnings("unchecked") public T acquire() { if (mPoolSize > 0) { final int lastPooledIndex = mPoolSize - 1; T instance = (T) mPool[lastPooledIndex]; mPool[lastPooledIndex] = null; mPoolSize--; return instance; } return null; } @Override public boolean release(T instance) { if (isInPool(instance)) { throw new IllegalStateException("Already in the pool!"); } if (mPoolSize < mPool.length) { mPool[mPoolSize] = instance; mPoolSize++; return true; } return false; } private boolean isInPool(T instance) { for (int i = 0; i < mPoolSize; i++) { if (mPool[i] == instance) { return true; } } return false; } } /** * Synchronized) pool of objects. * * @param <T> The pooled type. */ public static class SynchronizedPool<T> extends SimplePool<T> { private final Object mLock = new Object(); /** * Creates a new instance. * * @param maxPoolSize The max pool size. * * @throws IllegalArgumentException If the max pool size is less than zero. */ public SynchronizedPool(int maxPoolSize) { super(maxPoolSize); } @Override public T acquire() { synchronized (mLock) { return super.acquire(); } } @Override public boolean release(T element) { synchronized (mLock) { return super.release(element); } } } }

原始碼很簡單,主要有Pool介面、SimplePool、SynchronizedPool組成,官方也給出了demo,直接上我的使用封裝:


import android.support.v4.util.Pools;
import com.sing.client.live_audio.entity.BaseChatMsgEntity;

/**
 * Created by mayi on 17/4/8.
 *
 * @Autor CaiWF
 * @Email [email protected]
 * @TODO UIGeter物件池
 */

public class UIGeterPoolModule {
    private Pools.SynchronizedPool<BaseChatMsgEntity> pool;
    private static UIGeterPoolModule uiGeterPoolModule;

    private UIGeterPoolModule() {
        pool = new Pools.SynchronizedPool<BaseChatMsgEntity>(55);
    }

    public static synchronized UIGeterPoolModule getInstance() {
        if (uiGeterPoolModule == null) {
            uiGeterPoolModule = new UIGeterPoolModule();
        }
        return uiGeterPoolModule;
    }

    public Pools.SynchronizedPool<BaseChatMsgEntity> getPool() {
        return pool;
    }

    //物件池中獲取物件
    public static BaseChatMsgEntity getUIGetObject() {
        try {
            BaseChatMsgEntity baseChatMsgEntity = getInstance().getPool().acquire();
            return baseChatMsgEntity == null ? new BaseChatMsgEntity() : baseChatMsgEntity;
        } catch (Exception e) {
//            e.printStackTrace();
            return new BaseChatMsgEntity();
        }
    }

    //返回物件
    public static void returnObject(BaseChatMsgEntity uiGeter) {
        try {
            getInstance().getPool().release(uiGeter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

僅此做個筆記,有什麼不對的,歡迎指點!