GenericObjectPool參數解析

本文主要解析一下apache common pools下的GenericObjectPool的參數設置java

GenericObjectPool

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

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

默認配置見
commons-pool2-2.4.2-sources.jar!/org/apache/commons/pool2/impl/GenericObjectPoolConfig.javasegmentfault

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.javaide

public GenericObjectPool(PooledObjectFactory<T> 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<PooledObject<T>>(config.getFairness());

        setConfig(config);

        startEvictor(getTimeBetweenEvictionRunsMillis());
    }

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

/**
     * 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<T> implements EvictionPolicy<T> {

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

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

這裏就用到了上面提到的兩個參數.net

doc

相關文章
相關標籤/搜索