gpt4 book ai didi

Java在超时后释放Poolable对象

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:47 26 4
gpt4 key购买 nike

我一直在寻找池化对象的方法,如果 X 分钟内不使用该对象,它将从对象池中删除。

这个 Poolable 对象是到遗留系统的套接字连接。我只需要一个持久连接,当需要新连接时,会创建更多对象来满足该需求。但我只希望这些新的非持久对象连接在最后一个请求后持续大约 5 分钟,然后优雅地断开连接。

我不确定 Apache Commons Pool 项目是否可以在这里提供帮助。

如何设置这种“创建/发布”规则?它是 Apache Commons Pool 的一部分,还是我的对象必须自己处理它?我真的不确定。

-以色列

最佳答案

为了 future 读者的利益,我使用 commons pool2 编写了一个小型实现:

package com.test.communicator;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class Test {

public void initializePool() throws Exception {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();

// parameters for the life cycle of the objects
config.setMinIdle(1);
config.setMaxIdle(1);
config.setMaxTotal(1);

// if the object is not accessed in 5 minutes, it evicted (throw away from the pool)
config.setTimeBetweenEvictionRunsMillis(5 * 60 * 1000);
// frequency at which it check for objects to be evicted
config.setMinEvictableIdleTimeMillis(1 * 60 * 1000);

CommonsObjectPool pool = new CommonsObjectPool(new MyObjectPoolFactory(), config);

MyObject myObj = pool.borrowObject(); //borrow an object
}

/**
* An object pool implementation of your objects
*/
class CommonsObjectPool extends GenericObjectPool<MyObject> {

public CommonsObjectPool(PooledObjectFactory<MyObject> factory) {
super(factory);
}

public CommonsObjectPool(PooledObjectFactory<MyObject> factory, GenericObjectPoolConfig config) {
super(factory, config);
}
}



/**
* Factory to create the objects
*/
class MyObjectPoolFactory extends BasePooledObjectFactory<MyObject> {
@Override
public MyObject create() throws Exception {
// create your object
return new MyObject();
}

@Override
public PooledObject<MyObject> wrap(MyObject arg0) {
return new DefaultPooledObject<MyObject>(arg0);
}

@Override
public boolean validateObject(PooledObject<MyObject> pooledObj) {
return pooledObj.getObject().isMyObjectValid(); // implement a validation
}

@Override
public void destroyObject(PooledObject<MyObject> pooledObj) throws Exception {
// clean up the object
//pooledObj.getObject().close ()
}
}

class MyObject {
public boolean isMyObjectValid() {
return true;
}

public void close () {
// clean up the object
}
}
}

下面两行提供了您正在寻找的功能。

    // if the object is not accessed in 5 minutes, it evicted (throw away from the pool)
config.setTimeBetweenEvictionRunsMillis(5 * 60 * 1000);
// frequency at which it check for objects to be evicted
config.setMinEvictableIdleTimeMillis(1 * 60 * 1000);

关于Java在超时后释放Poolable对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18886085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com