java object pool
public final class ObjectPool<T> {
private static final String TAG = ObjectPool.class.getName();
private String poolName;
private Queue<T> objects;
private ObjectFactory<T> objectFactory;
public ObjectPool(@NonNull ObjectFactory<T> factory, @Nullable String poolName) {
objects = new ConcurrentLinkedQueue<>();
this.objectFactory = factory;
this.poolName = null != poolName && !poolName.isEmpty() ? poolName : TAG;
}
public synchronized T acquire() {
if (objects.isEmpty()) {
T t = objectFactory.newObject();
return t;
} else {
return objects.poll();
}
}
public void release(T object) {
if (!objects.contains(object)) {
objects.offer(object);
}
}
public void clear() {
objects.clear();
}
public interface ObjectFactory<V> {
V newObject();
}
}