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;
|
}
|
}
|