gpt4 book ai didi

java - 公共(public)资源池 : How to instantiate a concrete pool?

转载 作者:行者123 更新时间:2023-11-29 07:14:29 26 4
gpt4 key购买 nike

我已将 commons-pooling-1.6.jar 添加到我的类路径并尝试实例化一个 StackObjectPool 但每次都失败:

// Deprecated.
ObjectPool<T> oPool = new StackObjectPool<T>();

// Error: Cannot instantiate the type BasePoolableObjectFactory<T>.
PoolableObjectFactory<T> oFact = new BasePoolableObjectFactory<T>();
ObjectPool<T> oPool = new StackObjectPool<T>(oFact);

这是完全弃用的 API 吗?如果是这样,Commons Pooling 有哪些开源替代方案?否则,如何实例化 StackObjectPool

最佳答案

您需要编写自己的工厂,可能会扩展 BasePoolableObjectFactory。有关详细信息,请参见此处:http://commons.apache.org/pool/examples.html

下面是创建 StringBuffers 的 PoolableObjectFactory 实现:

import org.apache.commons.pool.BasePoolableObjectFactory; 

public class StringBufferFactory extends BasePoolableObjectFactory<StringBuffer> {
// for makeObject we'll simply return a new buffer
public StringBuffer makeObject() {
return new StringBuffer();
}

// when an object is returned to the pool,
// we'll clear it out
public void passivateObject(StringBuffer buf) {
buf.setLength(0);
}

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

然后按如下方式使用:

new StackObjectPool<StringBuffer>(new StringBufferFactory())

关于java - 公共(public)资源池 : How to instantiate a concrete pool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10837713/

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