资讯专栏INFORMATION COLUMN

GenericObjectPool参数解析

huayeluoliuhen / 754人阅读

摘要:如果为负值,表示不运行检测线程。默认为策略的类名,默认为这里就用到了上面提到的两个参数对象池原理分析避免泄漏配置参数详解,以及资源回收,从池中获取资源,将资源返还给池逻辑解析

本文主要解析一下apache common pools下的GenericObjectPool的参数设置

GenericObjectPool

commons-pool2-2.4.2-sources.jar!/org/apache/commons/pool2/impl/GenericObjectPool.java

public class GenericObjectPool extends BaseGenericObjectPool
        implements ObjectPool, GenericObjectPoolMXBean, UsageTracking {
   //......
}        

默认配置见
commons-pool2-2.4.2-sources.jar!/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java

public class GenericObjectPoolConfig extends BaseObjectPoolConfig {

    /**
     * The default value for the {@code maxTotal} configuration attribute.
     * @see GenericObjectPool#getMaxTotal()
     */
    public static final int DEFAULT_MAX_TOTAL = 8;

    /**
     * The default value for the {@code maxIdle} configuration attribute.
     * @see GenericObjectPool#getMaxIdle()
     */
    public static final int DEFAULT_MAX_IDLE = 8;

    /**
     * The default value for the {@code minIdle} configuration attribute.
     * @see GenericObjectPool#getMinIdle()
     */
    public static final int DEFAULT_MIN_IDLE = 0;


    private int maxTotal = DEFAULT_MAX_TOTAL;

    private int maxIdle = DEFAULT_MAX_IDLE;

    private int minIdle = DEFAULT_MIN_IDLE;

    //......
}
pool基本参数 基本参数

lifo
GenericObjectPool 提供了后进先出(LIFO)与先进先出(FIFO)两种行为模式的池。默认为true,即当池中有空闲可用的对象时,调用borrowObject方法会返回最近(后进)的实例

fairness
当从池中获取资源或者将资源还回池中时 是否使用java.util.concurrent.locks.ReentrantLock.ReentrantLock 的公平锁机制,默认为false

数量控制参数

maxTotal
链接池中最大连接数,默认为8

maxIdle
链接池中最大空闲的连接数,默认也为8

minIdle
连接池中最少空闲的连接数,默认为0

超时参数

maxWaitMillis
当连接池资源耗尽时,等待时间,超出则抛异常,默认为-1即永不超时

blockWhenExhausted
当这个值为true的时候,maxWaitMillis参数才能生效。为false的时候,当连接池没资源,则立马抛异常。默认为true

test参数

testOnCreate
默认false,create的时候检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取

testOnBorrow
默认false,borrow的时候检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取

testOnReturn
默认false,return的时候检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取

testWhileIdle
默认false,在evictor线程里头,当evictionPolicy.evict方法返回false时,而且testWhileIdle为true的时候则检测是否有效,如果无效则移除

检测参数

timeBetweenEvictionRunsMillis
空闲链接检测线程检测的周期,毫秒数。如果为负值,表示不运行检测线程。默认为-1.

commons-pool2-2.4.2-sources.jar!/org/apache/commons/pool2/impl/GenericObjectPool.java

public GenericObjectPool(PooledObjectFactory factory,
            GenericObjectPoolConfig config) {

        super(config, ONAME_BASE, config.getJmxNamePrefix());

        if (factory == null) {
            jmxUnregister(); // tidy up
            throw new IllegalArgumentException("factory may not be null");
        }
        this.factory = factory;

        idleObjects = new LinkedBlockingDeque>(config.getFairness());

        setConfig(config);

        startEvictor(getTimeBetweenEvictionRunsMillis());
    }

commons-pool2-2.4.2-sources.jar!/org/apache/commons/pool2/impl/BaseGenericObjectPool.java

/**
     * The idle object evictor {@link TimerTask}.
     *
     * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis
     */
    class Evictor extends TimerTask {
        /**
         * Run pool maintenance.  Evict objects qualifying for eviction and then
         * ensure that the minimum number of idle instances are available.
         * Since the Timer that invokes Evictors is shared for all Pools but
         * pools may exist in different class loaders, the Evictor ensures that
         * any actions taken are under the class loader of the factory
         * associated with the pool.
         */
        @Override
        public void run() {
            ClassLoader savedClassLoader =
                    Thread.currentThread().getContextClassLoader();
            try {
                if (factoryClassLoader != null) {
                    // Set the class loader for the factory
                    ClassLoader cl = factoryClassLoader.get();
                    if (cl == null) {
                        // The pool has been dereferenced and the class loader
                        // GC"d. Cancel this timer so the pool can be GC"d as
                        // well.
                        cancel();
                        return;
                    }
                    Thread.currentThread().setContextClassLoader(cl);
                }

                // Evict from the pool
                try {
                    evict();
                } catch(Exception e) {
                    swallowException(e);
                } catch(OutOfMemoryError oome) {
                    // Log problem but give evictor thread a chance to continue
                    // in case error is recoverable
                    oome.printStackTrace(System.err);
                }
                // Re-create idle instances.
                try {
                    ensureMinIdle();
                } catch (Exception e) {
                    swallowException(e);
                }
            } finally {
                // Restore the previous CCL
                Thread.currentThread().setContextClassLoader(savedClassLoader);
            }
        }
    }

numTestsPerEvictionRun
在每次空闲连接回收器线程(如果有)运行时检查的连接数量,默认为3

private int getNumTests() {
        int numTestsPerEvictionRun = getNumTestsPerEvictionRun();
        if (numTestsPerEvictionRun >= 0) {
            return Math.min(numTestsPerEvictionRun, idleObjects.size());
        } else {
            return (int) (Math.ceil(idleObjects.size() /
                    Math.abs((double) numTestsPerEvictionRun)));
        }
    }

minEvictableIdleTimeMillis
连接空闲的最小时间,达到此值后空闲连接将可能会被移除。默认为1000L 60L 30L

softMinEvictableIdleTimeMillis
连接空闲的最小时间,达到此值后空闲链接将会被移除,且保留minIdle个空闲连接数。默认为-1.

evictionPolicyClassName
evict策略的类名,默认为org.apache.commons.pool2.impl.DefaultEvictionPolicy

public class DefaultEvictionPolicy implements EvictionPolicy {

    @Override
    public boolean evict(EvictionConfig config, PooledObject underTest,
            int idleCount) {

        if ((config.getIdleSoftEvictTime() < underTest.getIdleTimeMillis() &&
                config.getMinIdle() < idleCount) ||
                config.getIdleEvictTime() < underTest.getIdleTimeMillis()) {
            return true;
        }
        return false;
    }
}

这里就用到了上面提到的两个参数

doc

Apache commons-pool对象池原理分析

GenericObjectPool 避免泄漏

apache-common-pool2(配置参数详解,以及资源回收,从池中获取资源,将资源返还给池 逻辑解析)

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67806.html

相关文章

  • GenericObjectPool 避免泄漏

    摘要:实际应用中由于程序实现的问题,可能造成在一些极端的情况下出现没有被调用导致的泄漏问题。在的时候检查是否有泄漏的时候检查泄漏如果一个对象之后秒还没有返还给,认为是泄漏的对象秒运行一次维护任务 更多内容,请访问 https://my.oschina.net/u/5751... GenericObjectPool GenericObjectPool 是 Apache Commons Poo...

    Keven 评论0 收藏0
  • common-pool2 使用

    摘要:使用提供了中对象池管理方式,它们的使用方式基本一样,这里以对象池为例介绍其使用方式,一般实现自己的对象池需要经过个步骤实现接口该接口是一种工厂模式,实现其目的是让对象池通过该工厂模式创建管理的对象创建对象池实例创建对象池我们假设对象是一 common-pool2 使用 common-pool2提供了3中对象池管理方式,它们的使用方式基本一样,这里以GenericObjectPool对象...

    since1986 评论0 收藏0
  • 聊聊GenericObjectPool的泄露检测

    摘要:序本文主要聊聊的参数。主要用来做连接池的泄露检测用。的状态一般是用于连接泄露的检测,检测的是在使用的对象,比如怀疑那个对象被占用时间超长,那估计是程序异常或导致对象了但忘记归还,或者对象之后使用时间太长。 序 本文主要聊聊GenericObjectPool的abandon参数。主要用来做连接池的泄露检测用。 object的状态 commons-pool2-2.4.2-sources.j...

    springDevBird 评论0 收藏0
  • JedisPool使用原理及源代码

    摘要:,的使用连接池的配置信息说明一个可以有多少个实例最大最小获得一个实例的时候是否检查连接可用性一个实例给时,是否检查连接可用性状态监测用异步线程进行检查,一次最多的里的实例个数 1,JedisPool的使用 //WHEN_EXHAUSTED_FAIL = 0; ...

    newtrek 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<