$ git clone https://git-wip-us.apache.org/repos/asf/commons-pool.git
核心的类及关系以下图: html
ObjectPool是对象池的接口,定义了很是简单的接口,仅仅须要经过addObject添加对象borrowObject能够获取对象,returnObject归还对象,invalidateObject让对象失效。 实例以下:git
public class ObjectPoolTest { public static void main(String[] args) throws Exception { ObjectPool pool = new GenericObjectPool(); PoolableObjectFactory factory = new PoolableObjectFactory() { @Override public Object makeObject() throws Exception { return new Object(); } @Override public void destroyObject(Object obj) throws Exception { } @Override public boolean validateObject(Object obj) { return false; } @Override public void activateObject(Object obj) throws Exception { } @Override public void passivateObject(Object obj) throws Exception { } }; pool.setFactory(factory); pool.addObject(); Object obj = null; try { obj = pool.borrowObject(); //...use the object... } catch(Exception e) { // invalidate the object pool.invalidateObject(obj); // do not return the object to the pool twice obj = null; } finally { // make sure the object is returned to the pool if(null != obj) { pool.returnObject(obj); } } } }
上面的实例大体能够看到对象池的使用方法,就是初始化池、往池中放入对象、从池中取对象、归还对象和销毁对象几个操做。下面就通用的GenericObjectPool为例分析一下相关的操做apache
Config是GenericObjectPool的简单内部类,其打包了GenericObjectPool的基本配置,详细说明及默认值能够参见源码。数据结构
Latch用来控制对象到线程的分配顺序,以确保公平性。也就是说,对象按线程请求对象的顺序分配给线程。ide
GenericObjectPool将对象的make过程委托给PoolableObjectFactory工厂去作了,其全部构造方法中都有PoolableObjectFactory这个接口,也就是说若是想要实例化GenericObjectPool须要传入PoolableObjectFactory的实现线程
如上所述,addObject()方法若是在PoolableObjectFactory的实现为空时会抛出异常:code
if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); }
addObject()方法会调用PoolableObjectFactory实现类的makeObject()方法,并调用addObjectToPool()方法将对象放入对象池。htm
当池中有了对象以后,就能够取到了,若是没有会抛出异常对象
将对象放回池中blog
将对象destroy