android中使用对象池 ----- Pools

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caiwenfeng_for_23/article/details/69808263

最近在做音频直播间的优化,发现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();
        }
    }

}

仅此做个笔记,有什么不对的,欢迎指点!

猜你喜欢

转载自blog.csdn.net/caiwenfeng_for_23/article/details/69808263
今日推荐