对象池
This commit is contained in:
parent
6ff8c6be75
commit
4b746c3c01
|
@ -2,18 +2,40 @@ package com.example.catchTheLetters.utils;
|
||||||
|
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对象池(防止频繁创建对象触发GC,必须继承)
|
* 对象池(防止频繁创建对象触发GC,必须继承)
|
||||||
* @param <T> 对象类型
|
* @param <T> 对象类型
|
||||||
* @author spyn
|
* @author spyn
|
||||||
*/
|
*/
|
||||||
public abstract class ObjectPool<T> implements Iterable<T> {
|
public class ObjectPool<T> implements Iterable<T> {
|
||||||
private final ConcurrentLinkedQueue<T> pool;
|
/**
|
||||||
|
* 对象池
|
||||||
|
*/
|
||||||
|
private final ConcurrentLinkedDeque<T> pool;
|
||||||
|
|
||||||
public ObjectPool() {
|
/**
|
||||||
this.pool = new ConcurrentLinkedQueue<>();
|
* 创建对象委托
|
||||||
|
*/
|
||||||
|
private final Supplier<T> factory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 重置对象委托
|
||||||
|
*/
|
||||||
|
private final Consumer<T> reset;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造函数
|
||||||
|
* @param factory 创建对象委托
|
||||||
|
* @param reset 重置对象委托
|
||||||
|
*/
|
||||||
|
public ObjectPool(Supplier<T> factory, Consumer<T> reset) {
|
||||||
|
this.pool = new ConcurrentLinkedDeque<>();
|
||||||
|
this.factory = factory;
|
||||||
|
this.reset = reset;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -22,8 +44,8 @@ public abstract class ObjectPool<T> implements Iterable<T> {
|
||||||
*/
|
*/
|
||||||
public T borrowObject() {
|
public T borrowObject() {
|
||||||
T object;
|
T object;
|
||||||
if ((object = pool.poll()) == null) {
|
if ((object = pool.pollFirst()) == null) {
|
||||||
object = createObject();
|
object = (T) factory.get();
|
||||||
}
|
}
|
||||||
return object;
|
return object;
|
||||||
}
|
}
|
||||||
|
@ -36,15 +58,9 @@ public abstract class ObjectPool<T> implements Iterable<T> {
|
||||||
if (object == null) {
|
if (object == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.pool.offer(object);
|
this.pool.push(object);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 创建一个对象
|
|
||||||
* @return 新建的对象
|
|
||||||
*/
|
|
||||||
protected abstract T createObject();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 清空对象池
|
* 清空对象池
|
||||||
*/
|
*/
|
||||||
|
|
Loading…
Reference in New Issue