首页 > 代码库 > Apache Commons Pool2连接池代码
Apache Commons Pool2连接池代码
2013年,Apache Commons Pool 2.0 发布,这是一个完全重写的对象池的实现。实现的代码和原来差异很大,原来的一些例子就不能用了。按照上面的例子,用pool2的类和方法重写下。
ApacheCommons Pool 2.0 代码如下:
package test.ffm83.commons.pool;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
/**
* commons pool的简单实用,基于2.x版本
* 1. Factory BasePooledObjectFactory
* 2. Pool的配置 就是pool
* 3. Pool实例 Resource
* @author范芳铭
*/
public classPool2BaseUsage {
public static void main(String[] args) {
finalGenericObjectPool<Resource> pool =new GenericObjectPool<Resource>(
newTestPoolableObjectFactory());
pool.setMaxTotal(2);
for (int i = 0; i < 6; i++) {
new Thread(new Runnable() {
@Override
publicvoid run() {
try {
Resourceobj = pool.borrowObject();//注意,如果对象池没有空余的对象,那么这里会block
System.out.println(StringUtils.rightPad(obj.toString()+",获取对象", 50,"-"));
Thread.sleep(5000);
pool.returnObject(obj);//归还连接池资源
System.out.println(StringUtils.leftPad(obj.toString()+",归还对象", 50,"-"));
}catch(Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
/**
* commons pool的简单实用,基于2.x版本
* 1.x的 BasePoolableObjectFactory类修改为 BasePooledObjectFactory
* @author范芳铭
*/
static classTestPoolableObjectFactory extends BasePooledObjectFactory<Resource>{
@Override
public Resource create()throws Exception {
return new Resource();
}
@Override
publicPooledObject<Resource> wrap(Resource resource) {
return newDefaultPooledObject<Resource>(resource);
}
/**
* When an object is returned to the pool,clear the buffer.
*/
@Override
public voidpassivateObject(PooledObject<Resource> resource) {
//resource.getObject().setRid(-1);
}
}
static class Resource {
public static int id;
private int rid;
public Resource() {
synchronized (this) {
rid = id++;
}
}
public int getRid() {
returnrid;
}
public void setRid(int rid){
this.rid = rid;
}
@Override
public String toString() {
SimpleDateFormatdf = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
Stringstr = df.format(newDate()) +","+ "id:"+rid;
return str;
}
}
}
运行效果如下:
2014-12-19 15:51:58,id:1,获取对象---------------------
2014-12-19 15:51:58,id:0,获取对象---------------------
2014-12-19 15:52:03,id:0,获取对象---------------------
---------------------2014-12-1915:52:03,id:0,归还对象
---------------------2014-12-1915:52:03,id:1,归还对象
2014-12-19 15:52:03,id:1,获取对象---------------------
---------------------2014-12-1915:52:08,id:0,归还对象
2014-12-19 15:52:08,id:0,获取对象---------------------
---------------------2014-12-1915:52:08,id:1,归还对象
2014-12-19 15:52:08,id:1,获取对象---------------------
---------------------2014-12-1915:52:13,id:0,归还对象
---------------------2014-12-1915:52:13,id:1,归还对象
Apache Commons Pool2连接池代码