46 lines
947 B
Java
46 lines
947 B
Java
|
package com.example.catchTheLetters.utils;
|
|||
|
|
|||
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
|||
|
|
|||
|
/**
|
|||
|
* 对象池(防止频繁创建对象触发GC,必须继承)
|
|||
|
* @param <T> 对象类型
|
|||
|
* @author spyn
|
|||
|
*/
|
|||
|
public abstract class ObjectPool<T> {
|
|||
|
private final ConcurrentLinkedQueue<T> pool;
|
|||
|
|
|||
|
public ObjectPool() {
|
|||
|
this.pool = new ConcurrentLinkedQueue<>();
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 取出一个对象
|
|||
|
* @return 对象
|
|||
|
*/
|
|||
|
public T borrowObject() {
|
|||
|
T object;
|
|||
|
if ((object = pool.poll()) == null) {
|
|||
|
object = createObject();
|
|||
|
}
|
|||
|
return object;
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 存入一个对象
|
|||
|
* @param object 对象
|
|||
|
*/
|
|||
|
public void returnObject(T object) {
|
|||
|
if (object == null) {
|
|||
|
return;
|
|||
|
}
|
|||
|
this.pool.offer(object);
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 创建一个对象
|
|||
|
* @return 新建的对象
|
|||
|
*/
|
|||
|
protected abstract T createObject();
|
|||
|
}
|