commons-pool2自定义对象池使用
文章目录
一、简介
在java开发中,为了减少对象创建和销毁的开销,我们常常复用对象,如单例模式。在同时需要多个对象时,则采用池,如线程池、数据库连接池等。这里介绍基于apache的commons-pool2包来创建自定义的对象池。
二、准备
2.1 官网地址
官网地址:http://commons.apache.org/proper/commons-pool/
2.2 maven依赖包
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
三、commons-pool2池的关键方法和类
2.1 关键类和方法
2.1.1 池化对象工厂类
org.apache.commons.pool2.PooledObjectFactory,用于对象的创建、激活、钝化、销毁等操作。
2.1.2 默认池化对象包装类
org.apache.commons.pool2.impl.DefaultPooledObject,对实际对象进行包装,添加如状态等信息。
2.1.3 对象池类
org.apache.commons.pool2.impl.GenericObjectPool,对象池。
2.1.4 对象池控制类
org.apache.commons.pool2.impl.GenericObjectPoolConfig,用于控制如最大连接数,最大空闲数、最小空闲数等。
2.2 线程安全
commons-pool2包的对象池是线程安全的。
所有对象存在ConcurrentHashMap中;
空闲对象存在LinkedBlockingDeque中。位org.apache.commons.pool2.impl.GenericObjectPool类中的关键源码如下:
// --- configuration attributes --------------------------------------------
private volatile int maxIdle = GenericObjectPoolConfig.DEFAULT_MAX_IDLE;
private volatile int minIdle = GenericObjectPoolConfig.DEFAULT_MIN_IDLE;
private final PooledObjectFactory<T> factory;
// --- internal attributes -------------------------------------------------
/*
* 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<IdentityWrapper<T>, PooledObject<T>> allObjects =
new ConcurrentHashMap<IdentityWrapper<T>, PooledObject<T>>();
/*
* The combined count of the currently created objects and those in the
* process of being created. Under load, it may exceed {@link #_maxActive}
* if multiple threads try and create a new object at the same time but
* {@link #create()} will ensure that there are never more than
* {@link #_maxActive} objects created at any one time.
*/
private final AtomicLong createCount = new AtomicLong(0);
privat