现在很多第三方框架都使用common-pool2作为对象池。
这个框架有几个核心:
一:工作类,比如说connetion,比如说一个可以干活(work)的Person。
二:工厂类,生产Person的工厂。工厂类是基于PooledObjectFactory->BasePooledObjectFactory的
三:配置类,对象池活跃对象个数等信息都需要配置:所遇需要配置类,基于GenericObjectPoolConfig
四:对象池Pool,GenericObjectPool
实例讲解:
1 Person类。
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void work() {
System.out.println(name + " 在干活 ");
}
}2工厂类
public class PersonFactory extends BasePooledObjectFactory<Person> {
public Person create() throws Exception {
String name = Math.random() + "";
Person p = new Person();
p.setName(name);
return p;
}
public PooledObject<Person> wrap(Person obj) {
return new DefaultPooledObject<Person>(obj);
}
}3配置
public class MyPoolConfig extends GenericObjectPoolConfig {
//在构造方法中可以配置参数,一般会在spring的xml文件中配置bean的方式配置对象池信息
public MyPoolConfig() {
super();
}
}4测试运行
public class Main {
public static void main(String[] args) throws Exception {
// 实例化配置类
MyPoolConfig myPoolConfig = new MyPoolConfig();
// 设置最大工作人数
myPoolConfig.setMaxTotal(10);
// new 一个对象池。
GenericObjectPool<Person> personPool = new GenericObjectPool<>(
new PersonFactory(), myPoolConfig);
// 测试1;
while (true) {
// 取出对象进行工作,没有释放对象。
Person p = personPool.borrowObject();
p.work();
// 代码运行后显示,最多有10个不同的人在工作
}
}
}==
==
本文通过一个具体的示例介绍了如何使用Common-Pool2框架实现对象池。具体包括定义工作类Person、创建Person工厂类、配置对象池参数以及运行测试代码等内容。
1375

被折叠的 条评论
为什么被折叠?



