有关如何使用Java ObjectPool /池的任何好的教程或示例吗?

时间:2012-04-28 23:02:35

标签: java connection-pooling

我正在尝试创建一个到队列服务器的通道/连接池,并且正在尝试使用ObjectPool,但在使用其网站上的example时遇到问题。

到目前为止,我的线程确实有效但我希望每个线程从池中获取一个通道然后返回它。我理解如何使用它(borrowObject / returnObjects),但不知道如何创建初始池。

以下是如何在rabbitmq中制作频道:

ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

我的代码只使用频道来做事。我很困惑,因为我能找到的唯一例子(在他们的网站上)就像这样开始:

private ObjectPool<StringBuffer> pool;

    public ReaderUtil(ObjectPool<StringBuffer> pool) { 
        this.pool = pool;
    }

这对我没有意义。我意识到这对于建立数据库连接是很常见的,所以我试图使用数据库和ObjectPool找到教程,但他们似乎使用特定于数据库的DBCP(我似乎无法使用我的队列服务器的逻辑)。

有关如何使用它的任何建议?或者是否有另一种方法用于java中的池?

2 个答案:

答案 0 :(得分:4)

他们创建了一个创建对象的类。知道返回时该怎么做。对你来说可能是这样的:

public class PoolConnectionFactory extends BasePoolableObjectFactory<Connection> { 

    private final ConnectionFactory factory;
    public PoolConnectionFactory() {
        factory = new ConnectionFactory();
        factory.setHost("localhost");
    }

    // for makeObject we'll simply return a new Connection
    public Connection makeObject() { 
        return factory.newConnection();
    } 

    // when an object is returned to the pool,  
    // we'll clear it out 
    public void passivateObject(Connection con) { 
        con.I_don't_know_what_to_do(); 
    } 

    // for all other methods, the no-op  
    // implementation in BasePoolableObjectFactory 
    // will suffice 
}

现在你在某处创建ObjectPool<Connection>

ObjectPool<Connection> pool = new StackObjectPool<Connection>(new PoolConnectionFactory());

然后你可以在你的线程中使用pool,如

Connection c = pool.borrowObject();
c.doSomethingWithMe();
pool.returnObject(c);

对您没有意义的行是将池对象传递给其他类的一种方法。查看最后一行,他们在创建阅读器时创建池。

new ReaderUtil(new StackObjectPool<StringBuffer>(new StringBufferFactory()))

答案 1 :(得分:3)

您需要PoolableObjectFactory的自定义实现来创建,验证和销毁要池的对象。然后将工厂的实例传递给ObjectPool的构造函数,然后就可以开始借用对象了。

这是一些示例代码。您还可以查看commons-dbcp的源代码,它使用commons-pool。

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;

public class PoolExample {
    public static class MyPooledObject {
        public MyPooledObject() {
            System.out.println("hello world");
        }

        public void sing() {
            System.out.println("mary had a little lamb");
        }

        public void destroy() {
            System.out.println("goodbye cruel world");
        }
    }

    public static class MyPoolableObjectFactory extends BasePoolableObjectFactory<MyPooledObject> {
        @Override
        public MyPooledObject makeObject() throws Exception {
            return new MyPooledObject();
        }

        @Override
        public void destroyObject(MyPooledObject obj) throws Exception {
            obj.destroy();
        }
        // PoolableObjectFactory has other methods you can override
        // to valdiate, activate, and passivate objects.
    }

    public static void main(String[] args) throws Exception {
        PoolableObjectFactory<MyPooledObject> factory = new MyPoolableObjectFactory();
        ObjectPool<MyPooledObject> pool = new GenericObjectPool<MyPooledObject>(factory);

        // Other ObjectPool implementations with special behaviors are available;
        // see the JavaDoc for details

        try {
            for (int i = 0; i < 2; i++) {
                MyPooledObject obj;

                try {
                    obj = pool.borrowObject();
                } catch (Exception e) {
                    // failed to borrow object; you get to decide how to handle this
                    throw e;
                }

                try {
                    // use the pooled object
                    obj.sing();

                } catch (Exception e) {
                    // this object has failed us -- never use it again!
                    pool.invalidateObject(obj);
                    obj = null; // don't return it to the pool

                    // now handle the exception however you want

                } finally {
                    if (obj != null) {
                        pool.returnObject(obj);
                    }
                }
            }
        } finally {
            pool.close();
        }
    }
}