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

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

程序员文章站 2024-03-15 10:26:59
...

改造上一篇的代码,实现了KeyedObjectPool.

 

对象池实现类

package com.my.pool.pooledobject;

import org.apache.commons.pool2.KeyedObjectPool;

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

 

工厂类:

package com.my.pool.pooledobject;

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

/**
 * 先创建,后打包
 *
 */
public class KeyedPooledStringBufferFactory extends BaseKeyedPooledObjectFactory<String,StringBuffer>{

	@Override
	public StringBuffer create(String key) throws Exception {
		StringBuffer buf = new StringBuffer();
		//根据key的不同进行不同的操作
		if("hello".equals(key)) {
			buf.append(key);
			buf.append("\t");
		}else {
			//Do nothing.
		}
		return buf;
	}

	@Override
	public PooledObject<StringBuffer> wrap(StringBuffer obj) {
		return new DefaultPooledObject<StringBuffer>(obj);
	}
	
	@Override
	/**
	 * 归还后调用的方法
	 */
	public void passivateObject(String key,PooledObject<StringBuffer> pooledObject) {
		StringBuffer buf = pooledObject.getObject();
		buf.setLength(0);
		if("hello".equals(key)) {
			buf.append(key);
			buf.append("\t");
		}else {
			//Do nothing.
		}
	}
}

 

主类:

package com.my.pool.main;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;

import com.my.pool.pooledobject.KeyedPooledStringBuffer;
import com.my.pool.pooledobject.KeyedPooledStringBufferFactory;

public class KeyedMainClass {
	public static void main(String[] args) {
		GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
		//最长等待分配时间
		config.setMaxWaitMillis(1000l);
		//每种key池内最多对象数
		config.setMaxTotalPerKey(100);
		//每种key池内最大空闲数目
		config.setMaxIdlePerKey(20);
		//每种key池内最小空闲数目
		config.setMinIdlePerKey(10);
		
		GenericKeyedObjectPool<String,StringBuffer> pool = new GenericKeyedObjectPool<String,StringBuffer>(new KeyedPooledStringBufferFactory());
		
		KeyedPooledStringBuffer bufUtil = new KeyedPooledStringBuffer(pool);
		bufUtil.print("hello","OK");
		bufUtil.print("else","OK");
	}
}

 

      KeyedObjectPool和ObjectPool的区别在于对于输入的key可以做不一样的操作,甚至获得不同的线程池。本例是在创建的时候,加入了一些字符,并在回收之后把前缀又写回去。不同的用法,可以自己发挥想象。