Assume the server is sending data to our app at regular intervals, at least once per second. The received data is parsed and stored in memory as a POJO. A blocking queue is processing data in a worker thread.
Suppose I want to use a very simple object pool, so I don’t have to create a new POJO for each server response. I don’t want to use e.g. Apache Commons Pool.
Would the following implementation suffice?
public abstract class ObjectPool<T> {
private final Stack<T> mPool;
public ObjectPool() {
mPool = new Stack<T>();
}
public T obtain() {
if (mPool.isEmpty()) {
return create();
} else {
return mPool.pop();
}
}
public void recycle(T object) {
if (null != object) {
destroy(object);
mPool.push(object);
}
}
public void clear() {
mPool.clear();
}
public int getSize() {
return mPool.size();
}
protected abstract T create();
protected abstract void destroy(T object);
}
Can I shoot myself in the foot using this? Any caveats I’m not seeing?
Thanks!