对象池

来源:互联网 发布:java ssh 书籍 编辑:程序博客网 时间:2024/05/18 00:21

java中有些对象需要频繁创建和销毁,为了性能考虑可以使用对象池复用这些对象。
1、创建一个管理对象的类

/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.android.providers.certinstaller.util;//使用对象池Pools http://www.jianshu.com/p/b981bb758d43/**对象池源码*///http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/android/support/v4/util/Pools.java/** * Helper class for crating pools of objects. An example use looks like this: * <pre> * public class MyPooledClass { * *     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);            }        }    }}

2、使用对象池来管理对象

public class BannerAdPlay extends AdPlayParent{    //使用对象池Pools http://www.jianshu.com/p/b981bb758d43    private static final SynchronizedPool<BannerAdPlay> sPool =    new  SynchronizedPool<BannerAdPlay>(10);    public static BannerAdPlay obtain() {//创建对象        BannerAdPlay instance = sPool.acquire();        LogUtil.i(ISLOG,TAG,"--obtain instance  "+instance);        return (instance != null) ? instance : new BannerAdPlay();    }    @Override    public void recycle() {//使用完毕务必要将对象归还到对象池        sPool.release(this);    }    private BannerAdPlay(){//使外部不能直接new    }

3、效果分析
使用了对象池之后,每次都复用这个对象,大大提升性能。

原创粉丝点击