org.ak.trafficController.pool.ObjectPool Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of memory-pool Show documentation
Show all versions of memory-pool Show documentation
This deals with different aspects like In memory queue, throttling, event management etc
package org.ak.trafficController.pool;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
public class ObjectPool {
private Supplier generator;
private AtomicInteger count = new AtomicInteger();
private int poolSize = 2000;
public ObjectPool(Supplier generator) {
if (generator == null) throw new RuntimeException("Generator cant be null");
this.generator = generator;
}
private ConcurrentLinkedQueue pool = new ConcurrentLinkedQueue();
public void addBackToPool(T obj) {
if (count.get() < poolSize) {
count.incrementAndGet();
pool.add(obj);
} //else ignore.
}
public T getFromPool() {
T obj = pool.poll();
if (obj == null) {
return generator.get();
} else {
count.decrementAndGet();
}
return obj;
}
public int getCount() {
return pool.size();
}
public ObjectPool setSize(int size) {
this.poolSize = size;
return this;
}
}