Object pool pattern
Object pool allows to reuse and share objects that are expensive to create.
problems
Suppose creation of object is expensive like connection for database. When such objects are used in a short time, application performance may decline.
Languages like Java have garbage collector that removes unused objects. When it try delete many objects at once, application can be hang.
To solve such problems, a object pool is used. It usually represents container with the ability to create a new object, take out the object and put the object back after use.
advantages
- Performance boost.
- Reduces used resources or control its number.
import java.util.concurrent.ConcurrentLinkedQueue;
public class DemoObjectPool<T> {
interface ObjectFactory<T> {
T newObject();
}
// LinkedList can be used for single-threaded application
private ConcurrentLinkedQueue<T> container = new ConcurrentLinkedQueue<>();
private ObjectFactory<T> objectFactory;
private int maxNumber = Integer.MAX_VALUE;
public DemoObjectPool() {
}
public DemoObjectPool(ObjectFactory<T> of, int number) {
maxNumber = number;
if (maxNumber <= 0) {
number = Integer.MAX_VALUE;
}
objectFactory = of;
}
protected T createObject() {
if (objectFactory != null) {
return objectFactory.newObject();
}
throw new IllegalStateException(
"Creating an object is not implemented;"+
" inherit a class or provide a object factory.");
}
public T borrowObject() {
T obj = container.poll();
if (obj == null) {
obj = createObject();
}
return obj;
}
public void returnObject(T obj) {
if (obj != null && container.size() < maxNumber) {
container.add(obj);
} else {
destroyObject(obj);
}
}
protected void destroyObject(T obj) {
}
}
Additionally a object pool can have
- method for object validation before borrow
- method for remove all objects
- a periodically task that adds or removes objects depending on conditions
- method for reset some object properties before returning
- a control how long time objects will be stored in pool