net.intelie.pipes.util.ObjectPool Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pipes-api Show documentation
Show all versions of pipes-api Show documentation
Intelie Pipes' API classes and interfaces
package net.intelie.pipes.util;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Supplier;
public class ObjectPool {
private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>();
private final Supplier factory;
private final int maxRetries;
@SuppressWarnings({"unused", "FieldCanBeLocal"})
private final List strong;
//keeping a strong reference to minPoolSize elements to avoid their collection
public ObjectPool(Supplier factory) {
this(factory, 1, 5);
}
public ObjectPool(Supplier factory, int minPoolSize, int maxRetries) {
this.maxRetries = maxRetries;
this.factory = factory;
this.strong = initMinPool(factory, minPoolSize);
}
private List initMinPool(Supplier factory, int minPoolSize) {
List strong = new ArrayList<>();
for (int i = 0; i < minPoolSize; i++) {
try (Ref ref = new Ref(factory.get())) {
strong.add(ref.obj());
}
}
return strong;
}
public Ref acquire() {
Ref ref = null;
for (int i = 0; i < maxRetries; i++) {
ref = queue.poll();
//either empty pool or valid deref'd object
if (ref == null || ref.materialize()) break;
ref = null;
}
if (ref == null)
ref = new Ref(factory.get());
return ref;
}
public class Ref implements SafeCloseable {
private final SoftReference ref;
private T obj;
private Ref(T obj) {
this.ref = new SoftReference<>(obj);
this.obj = obj;
}
private boolean materialize() {
this.obj = ref.get();
return this.obj != null;
}
public T obj() {
return obj;
}
@Override
public void close() {
if (obj == null) return;
obj = null;
queue.offer(this);
}
}
}