endian11
2019-12-30 6a6056c49f4b94018081b9a9462df1bd477971a6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package safeluck.drive.evaluation.cEventCenter;
 
/**
 * 自定义的对象池
 * MyApplication2
 * Created by lzw on 2019/12/30. 17:06:49
 * 邮箱:632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public abstract class ObjectPool<T extends PooledObject> {
 
    private T[] mContainer;//对象容器
 
    private final Object LOCK = new Object();//对象锁
 
    private int length;//每次返回对象都放到数据末端,length表示前面可用对象数
 
    public ObjectPool(int capacity) {
        mContainer = createObjPool(capacity);
    }
 
    /**
     * 创建对象池
     * @param capacity 最大限度容量
     * @return
     */
    protected abstract T[] createObjPool(int capacity) ;
 
    /**
     * 创建一个新的对象
     * @return
     */
    protected abstract T createNewObj();
 
 
    public final T get(){
        //先从池中找到空闲的对象,如果没有,则重新创建一个对象
        T obj = findFreeObject();
        if (null == obj){
            obj = createNewObj();
        }else{
            obj.reset();
        }
        return obj;
    }
 
    /**
     * 从池中找到空闲的对象
     * @return
     */
    private T findFreeObject() {
        T obj = null;
        synchronized (LOCK){
            if (length > 0 ){
                --length;
                obj = mContainer[length];
                //赋值完成后释放资源
                mContainer[length] = null;
            }
        }
        return obj;
    }
}