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:池對象工廠,負責池對象的建立,銷燬等.