All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ak.trafficController.pool.ObjectPool Maven / Gradle / Ivy

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;
	}
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy