Apache common-pool2提供了一个通用的对象池技术的实现。html
common-pool2主要围绕三个接口来实现,ObjectPool、PooledObject、PooledObjectFactory。由PooledObjectFactory建立的对象,经PooledObject包装后放入ObjectPool。java
ObjectPool:对象池,负责存放管理对象.node
官方例子:http://commons.apache.org/proper/commons-pool/examples.htmlapache
ReaderUtil readerUtil = new ReaderUtil(new GenericObjectPool<StringBuffer>(new StringBufferFactory()));
先从GenericObjectPool开始分析数据结构
成员变量:app
重要的成员变量为:allObjects和idleObjects.less
/* * All of the objects currently associated with this pool in any state. It * excludes objects that have been destroyed. The size of * {@link #allObjects} will always be less than or equal to {@link * #_maxActive}. Map keys are pooled objects, values are the PooledObject * wrappers used internally by the pool. */ private final Map<T, PooledObject<T>> allObjects = new ConcurrentHashMap<T, PooledObject<T>>();
private final LinkedBlockingDeque<PooledObject<T>> idleObjects;
allObjects:对象池中全部的对象.
this
idleObjects:空闲对象.spa
其中数据结构LinkedBlockingDeque:code
结点的数据结构
/** Doubly-linked list node class */ private static final class Node<E> { /** * The item, or null if this node has been removed. */ E item; /** * One of: * - the real predecessor Node * - this Node, meaning the predecessor is tail * - null, meaning there is no predecessor */ Node<E> prev; /** * One of: * - the real successor Node * - this Node, meaning the successor is head * - null, meaning there is no successor */ Node<E> next; /** * Create a new list node. * * @param x The list item * @param p Previous item * @param n Next item */ Node(E x, Node<E> p, Node<E> n) { item = x; prev = p; next = n; } }
PooledObject:池对象,将须要放入对象池的对象包装添加一些附加信息.
从以前的分析中能够看出GenericObjectPool中allObjects和idleObjects存放均是池对象即通过包装的对象.
private final Map<T, PooledObject<T>> allObjects = new ConcurrentHashMap<T, PooledObject<T>>(); private final LinkedBlockingDeque<PooledObject<T>> idleObjects;
PooledObjectFactory:池对象工厂,负责池对象的建立,销毁等.