commons pool2 之GenericObjectPool(未完)

Apache Commons Pool2中的GenericObjectPool是一个对象池实现,它利用ConcurrentHashMap存储对象,通过IdentityWrapper作为键,避免因对象hashCode方法不理想导致的哈希冲突。此外,它使用阻塞队列存储空闲对象,队列可在构造时配置为公平或非公平锁模式,以优化性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

commons pool2 的org.apache.commons.pool2.impl包下提供了一个对象池的具体实现GenericObjectPool。

类内部使用一个ConcurrentHashmap存储所有的objects:

private final Map<IdentityWrapper<T>, PooledObject<T>> allObjects =
        new ConcurrentHashMap<IdentityWrapper<T>, PooledObject<T>>();

其中使用了一个包裹类IdentityWrapper作为map的key,该类是GenericObjectPool的一个static类:

static class IdentityWrapper<T> {
        /** Wrapped object */
        private final T instance;
        ...
        @Override
        public int hashCode() {
            return System.identityHashCode(instance);
        }
        @Override
        @SuppressWarnings("rawtypes")
        public boolean equals(Object other) {
            return ((IdentityWrapper) other).instance == instance;
        }
        ...

之所以用一个类又把对象包裹了一层来作为map的key,是防止GenericObjectPool中存放的对象没有很好的实现其hashCode方法,有可能会使map产生大量hash冲突,降低map存取元素的效率。

用一个阻塞队列来保存idle空闲对象:

private final LinkedBlockingDeque<PooledObject<T>> idleObjects;

阻塞队列在GenericObjectPool构造方法中初始化:

public GenericObjectPool(PooledObjectFactory<T> factory,
            GenericObjectPoolConfig config) {
...
idleObjects = new LinkedBlockingDeque<PooledObject<T>>(config.getFairness());
...

从源码中可以看出,可以将阻塞队列配置成非公平锁模式或者公平锁模式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值