2024-04-08 10:51:09 +00:00
|
|
|
|
package com.example.catchTheLetters.utils;
|
|
|
|
|
|
2024-04-08 14:50:55 +00:00
|
|
|
|
import org.jetbrains.annotations.NotNull;
|
|
|
|
|
|
2024-04-08 10:51:09 +00:00
|
|
|
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 对象池(防止频繁创建对象触发GC,必须继承)
|
|
|
|
|
* @param <T> 对象类型
|
|
|
|
|
* @author spyn
|
|
|
|
|
*/
|
2024-04-08 14:50:55 +00:00
|
|
|
|
public abstract class ObjectPool<T> implements Iterable<T> {
|
2024-04-08 10:51:09 +00:00
|
|
|
|
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();
|
2024-04-08 14:50:55 +00:00
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 清空对象池
|
|
|
|
|
*/
|
|
|
|
|
public void clear() {
|
|
|
|
|
this.pool.clear();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 覆写迭代器,便于遍历对象池
|
|
|
|
|
*/
|
|
|
|
|
@NotNull
|
|
|
|
|
@Override
|
|
|
|
|
public java.util.Iterator<T> iterator() {
|
|
|
|
|
return this.pool.iterator();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
public String toString() {
|
|
|
|
|
return this.pool.toString();
|
|
|
|
|
}
|
2024-04-08 10:51:09 +00:00
|
|
|
|
}
|