通过Apache common pool开源包实现对象池

来源:互联网 发布:博途v13编程手册 编辑:程序博客网 时间:2024/05/16 05:28

下面通过一个简单的样例来说明如何利用apache common pool来应用对象池。

假定我现在有一个任务,就是对一堆字符串进行格式化,为了加快速度,采用了多线程的方式允许,而格式化则是通过对象StringFormat来实现。

采用池技术,目的在于循环利用此对象,避免不停的生成和回收类。

也许本样例并不是很恰当,但是如何StringFormat换成是数据库连接就非常适合池技术了,此样例仅用于说明如何使用apache common pool池而已。


字符串格式化类:

public class StringFormat {public String format(String str){return "formated:"+str;}}


对象工厂:

import org.apache.commons.pool2.BasePooledObjectFactory;import org.apache.commons.pool2.PooledObject;import org.apache.commons.pool2.impl.DefaultPooledObject;public class StringFormatFactory    extends BasePooledObjectFactory<StringFormat> {    @Override    public StringFormat create() {    System.out.println("create object");        return new StringFormat();    }    /**     * Use the default PooledObject implementation.     */    @Override    public PooledObject<StringFormat> wrap(StringFormat buffer) {        return new DefaultPooledObject<StringFormat>(buffer);    }    /**     * When an object is returned to the pool, clear the buffer.     */    @Override    public void passivateObject(PooledObject<StringFormat> pooledObject) {    System.out.println("Object been returned to pool");    }    // for all other methods, the no-op implementation    // in BasePooledObjectFactory will suffice}


处理线程类:

import org.apache.commons.pool2.ObjectPool;public class StringProcessThread extends Thread {private ObjectPool<StringFormat> pool;private String toProcessStr;public StringProcessThread(ObjectPool<StringFormat> pool,String toProcessStr) {this.pool = pool;this.toProcessStr = toProcessStr;}public void run() {StringFormat stringFormat = null;try {stringFormat = pool.borrowObject();String formattedStr = stringFormat.format(toProcessStr);System.out.println(formattedStr);} catch (Exception e) {e.printStackTrace();} finally {try {if (stringFormat != null) {pool.returnObject(stringFormat);}} catch (Exception e) {e.printStackTrace();}}}}


主程序:

import java.io.IOException;import java.io.Reader;import java.util.ArrayList;import java.util.List;import org.apache.commons.pool2.ObjectPool;import org.apache.commons.pool2.impl.GenericObjectPool;public class StringProcessor {private ObjectPool<StringFormat> pool;public StringProcessor(ObjectPool<StringFormat> pool) {this.pool = pool;}/** * Dumps the contents of the {@link Reader} to a String, closing the * {@link Reader} when done. */public void process(List<String> strList) {for (String str : strList) {Thread thread = new StringProcessThread(pool, str);thread.start();}//设置等待两秒,等待线程结束try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) throws IOException {StringProcessor stringProcessor = new StringProcessor(new GenericObjectPool<StringFormat>(new StringFormatFactory()));List<String> strList = new ArrayList<String>();strList.add("123");strList.add("456");strList.add("789");stringProcessor.process(strList);}}



0 0
原创粉丝点击