对象池
This commit is contained in:
parent
6ff8c6be75
commit
4b746c3c01
|
@ -2,18 +2,40 @@ package com.example.catchTheLetters.utils;
|
|||
|
||||
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,必须继承)
|
||||
* @param <T> 对象类型
|
||||
* @author spyn
|
||||
*/
|
||||
public abstract class ObjectPool<T> implements Iterable<T> {
|
||||
private final ConcurrentLinkedQueue<T> pool;
|
||||
public class ObjectPool<T> implements Iterable<T> {
|
||||
/**
|
||||
* 对象池
|
||||
*/
|
||||
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() {
|
||||
T object;
|
||||
if ((object = pool.poll()) == null) {
|
||||
object = createObject();
|
||||
if ((object = pool.pollFirst()) == null) {
|
||||
object = (T) factory.get();
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
@ -36,15 +58,9 @@ public abstract class ObjectPool<T> implements Iterable<T> {
|
|||
if (object == null) {
|
||||
return;
|
||||
}
|
||||
this.pool.offer(object);
|
||||
this.pool.push(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个对象
|
||||
* @return 新建的对象
|
||||
*/
|
||||
protected abstract T createObject();
|
||||
|
||||
/**
|
||||
* 清空对象池
|
||||
*/
|
||||
|
|
Loading…
Reference in New Issue