【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
Apache common-pool2提供了一个通用的对象池技术的实现。
common-pool2主要围绕三个接口来实现,ObjectPool、PooledObject、PooledObjectFactory。由PooledObjectFactory创建的对象,经PooledObject包装后放入ObjectPool。
1.ObjectPool对象池
ObjectPool:对象池,负责存放管理对象.
官方例子:http://commons.apache.org/proper/commons-pool/examples.html
ReaderUtil readerUtil =
new ReaderUtil(new GenericObjectPool<StringBuffer>(new StringBufferFactory()));
先从GenericObjectPool开始分析
成员变量:
重要的成员变量为:allObjects和idleObjects.
/*
* 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:对象池中所有的对象.
idleObjects:空闲对象.
其中数据结构LinkedBlockingDeque:
结点的数据结构
/** 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;
}
}
2.PooledObject池对象
PooledObject:池对象,将需要放入对象池的对象包装添加一些附加信息.
从之前的分析中可以看出GenericObjectPool中allObjects和idleObjects存放均是池对象即经过包装的对象.
private final Map<T, PooledObject<T>> allObjects =
new ConcurrentHashMap<T, PooledObject<T>>();
private final LinkedBlockingDeque<PooledObject<T>> idleObjects;
3.PooledObjectFactory池对象工厂
PooledObjectFactory:池对象工厂,负责池对象的创建,销毁等.
来源:oschina
链接:https://my.oschina.net/u/657390/blog/648657