98 lines
3.1 KiB
Java
98 lines
3.1 KiB
Java
package de.thpeetz.tools;
|
|
|
|
import java.util.Vector;
|
|
import java.util.logging.Level;
|
|
import java.util.logging.Logger;
|
|
|
|
import de.thpeetz.network.osi.transport.RFC1006Service;
|
|
|
|
/**
|
|
* @author Thomas Peetz
|
|
*
|
|
* @param <T> type of objects in ObjectPool
|
|
*/
|
|
public class ObjectPool<T> {
|
|
/**
|
|
* Vector of unused object references.
|
|
*/
|
|
private final Vector<T> freeStack;
|
|
|
|
Logger logger;
|
|
|
|
/**
|
|
* Construct an object pool for a specific class type.
|
|
*
|
|
* @param clazz
|
|
* Class type of object pool
|
|
* @throws IllegalAccessException
|
|
* @throws InstantiationException
|
|
*/
|
|
public ObjectPool(final Class<T> clazz) {
|
|
this.freeStack = new Vector<T>();
|
|
init(clazz);
|
|
logger = Logger.getLogger(ObjectPool.class.getName());
|
|
|
|
}
|
|
|
|
/**************************************************************************
|
|
* Construct an object pool for a specific class type. Initialize object
|
|
* pool with given number of objects.
|
|
*
|
|
* @param clazz
|
|
* Class type of object pool
|
|
* @param size
|
|
* Initial number of objects in pool
|
|
* @throws IllegalAccessException
|
|
* @throws InstantiationException
|
|
***************************************************************************/
|
|
public ObjectPool(final Class<T> clazz, final int size) {
|
|
this.freeStack = new Vector<T>(size);
|
|
init(clazz);
|
|
}
|
|
|
|
/**************************************************************************
|
|
* Construct an object pool for a specific class type. Initialize object
|
|
* pool with number of objects equal to stack size.
|
|
*
|
|
* @param clazz
|
|
* Class type of object pool
|
|
***************************************************************************/
|
|
private void init(final Class<T> clazz) {
|
|
for (int i = 0; i < freeStack.capacity(); i++) {
|
|
try {
|
|
freeStack.add(i, clazz.newInstance());
|
|
} catch (InstantiationException e) {
|
|
logger.log(Level.FINE, e.getMessage());
|
|
} catch (IllegalAccessException e) {
|
|
logger.log(Level.FINE, e.getMessage());
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get instance from object pool.
|
|
*
|
|
* @return Reference of object
|
|
*/
|
|
public final synchronized T getInstance() {
|
|
// Check if the pool is empty.
|
|
if (this.freeStack.isEmpty()) {
|
|
return null;
|
|
}
|
|
// Remove object from end of free pool.
|
|
T result = this.freeStack.lastElement();
|
|
this.freeStack.setSize(this.freeStack.size() - 1);
|
|
return result;
|
|
}
|
|
|
|
/**************************************************************************
|
|
* Return object to object pool.
|
|
*
|
|
* @param obj
|
|
* Reference of unsed object
|
|
***************************************************************************/
|
|
public final synchronized void freeInstance(final T obj) {
|
|
this.freeStack.addElement(obj);
|
|
}
|
|
}
|