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

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

Go to download

This deals with different aspects like In memory queue, throttling, event management etc

There is a newer version: 2.1.0
Show newest version
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