欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

commons-pool对象池实例(一) 博客分类: java  

程序员文章站 2024-03-15 10:31:05
...

使用commons-pool 框架实现了一个对象池例子。将官网的例子稍微改动了一下而已。

使用的版本是:

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
	<version>2.4.2</version>
</dependency>

 

 

对象池实现类:

 

package com.my.pool.pooledobject;

import org.apache.commons.pool2.ObjectPool;

public class PooledStringBuffer {
	private ObjectPool<StringBuffer> pool;
	
	public PooledStringBuffer(ObjectPool<StringBuffer> pool) {
		this.pool = pool;
	}
	
	public boolean print(String data) {
		boolean flag = false;
		if(pool!=null) {
			StringBuffer buf = null;
			try{
				buf = pool.borrowObject();
				buf.append(data);
				System.out.println(buf.toString());
				return true;
			}catch(Exception e) {
				e.printStackTrace();
			}finally {
				try {
					pool.returnObject(buf);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return flag;
	}
	
}

 

对象池的工厂:

package com.my.pool.pooledobject;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 * 先创建,后打包
 *
 */
public class PooledStringBufferFactory extends BasePooledObjectFactory<StringBuffer>{

	@Override
	public StringBuffer create() throws Exception {
		return new StringBuffer();
	}

	@Override
	/**
	 * 打包成一个可以调度的对象
	 */
	public PooledObject<StringBuffer> wrap(StringBuffer obj) {
		return new DefaultPooledObject<StringBuffer>(obj);
	}
	
	@Override
	/**
	 * 归还后调用的方法
	 */
	public void passivateObject(PooledObject<StringBuffer> pooledObject) {
		pooledObject.getObject().setLength(0);
	}

}

 

主类:

package com.my.pool.main;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import com.my.pool.pooledobject.PooledStringBuffer;
import com.my.pool.pooledobject.PooledStringBufferFactory;

public class MainClass {
	public static void main(String[] args) {
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		//最长等待分配时间
		config.setMaxWaitMillis(1000l);
		//池内最多对象数
		config.setMaxTotal(100);
		//池内最大空闲数目
		config.setMaxIdle(20);
		//池内最小空闲数目
		config.setMinIdle(10);
		
		GenericObjectPool<StringBuffer> pool = new GenericObjectPool<StringBuffer>(new PooledStringBufferFactory(), config);
		
		PooledStringBuffer bufUtil = new PooledStringBuffer(pool);
		bufUtil.print("OK");
	}
}

 

    对象池可以应用于数据库连接池的管理,可以重复利用对象,提高性能。实际应用中使用spring进行配置管理会更方便