对象池common-pool2源码分析

Apache common-pool2提供了一个通用的对象池技术的实现。

common-pool2主要围绕三个接口来实现,ObjectPool、PooledObject、PooledObjectFactory。由PooledObjectFactory创建的对象,经PooledObject包装后放入ObjectPool。

1.ObjectPool对象池

ObjectPool:对象池,负责存放管理对象.

152516_fKWa_657390.png

官方例子:http://commons.apache.org/proper/commons-pool/examples.html

ReaderUtil readerUtil = 
        new ReaderUtil(new GenericObjectPool<StringBuffer>(new StringBufferFactory()));

先从GenericObjectPool开始分析

成员变量:

180626_Ilym_657390.png

重要的成员变量为:allObjects和idleObjects.

/*
 * All of the objects currently associated with this pool in any state. It
 * excludes objects that have been destroyed. The size of
 * {@link #allObjects} will always be less than or equal to {@link
 * #_maxActive}. Map keys are pooled objects, values are the PooledObject
 * wrappers used internally by the pool.
 */
private final Map<T, PooledObject<T>> allObjects =
        new ConcurrentHashMap<T, PooledObject<T>>();


private final LinkedBlockingDeque<PooledObject<T>> idleObjects;


allObjects:对象池中所有的对象.

idleObjects:空闲对象.

其中数据结构LinkedBlockingDeque:

163352_GQjv_657390.png

结点的数据结构

/** Doubly-linked list node class */
private static final class Node<E> {
    /**
     * The item, or null if this node has been removed.
     */
    E item;

    /**
     * One of:
     * - the real predecessor Node
     * - this Node, meaning the predecessor is tail
     * - null, meaning there is no predecessor
     */
    Node<E> prev;

    /**
     * One of:
     * - the real successor Node
     * - this Node, meaning the successor is head
     * - null, meaning there is no successor
     */
    Node<E> next;

    /**
     * Create a new list node.
     *
     * @param x The list item
     * @param p Previous item
     * @param n Next item
     */
    Node(E x, Node<E> p, Node<E> n) {
        item = x;
        prev = p;
        next = n;
    }
}
2.PooledObject池对象

PooledObject:池对象,将需要放入对象池的对象包装添加一些附加信息.

从之前的分析中可以看出GenericObjectPool中allObjects和idleObjects存放均是池对象即经过包装的对象.

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

154728_you1_657390.png

3.PooledObjectFactory池对象工厂

PooledObjectFactory:池对象工厂,负责池对象的创建,销毁等.

155456_vEyC_657390.png

转载于:https://my.oschina.net/u/657390/blog/648657

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值