Analysis of GenericObjectPool Parameters

  java

Order

This article mainly analyzes the parameter settings of GenericObjectPool under apache common pools.

GenericObjectPool

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

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

The default configuration is shown in
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 basic parameters

Basic parameter

  • lifo
    GenericObjectPool provides a pool of last in first out (LIFO) and first in first out (FIFO) behavior modes. The default is true, that is, when there are free objects available in the pool, calling the borrowObject method returns the most recent (backwardAn example of
  • fairness
    Whether to use the fair lock mechanism of Java.util.concurrent.locks.reentrant lock.reentrant lock when obtaining resources from the pool or returning resources to the pool, the default is false

Quantity control parameter

  • maxTotal
    The maximum number of connections in the link pool is 8 by default
  • maxIdle
    The maximum number of free connections in the link pool is also 8 by default
  • minIdle
    The minimum number of idle connections in the connection pool, which defaults to 0

Timeout parameter

  • maxWaitMillis
    When the connection pool resource is exhausted, the waiting time will be thrown if it exceeds, and the default value is -1, that is, it will never time out.
  • blockWhenExhausted
    When this value is true, the maxWaitMillis parameter will not take effect. When false, when the connection pool has no resources, the exception is thrown immediately. The default is true

Test parameter

  • testOnCreate
    The default is false. when create, the detection is valid. if it is invalid, it will be removed from the connection pool and try to get it and continue to get it.
  • testOnBorrow
    The default is false. borrow’s detection is valid. if it is not valid, it will be removed from the connection pool and will try to get it and continue to get it.
  • testOnReturn
    The default is false, and the detection is valid when returning. if it is invalid, it will be removed from the connection pool, and try to get it and continue to get it.
  • testWhileIdle
    The default is false. In the evictor thread, when the evictionPolicy.evict method returns false and testWhileIdle is true, it detects whether it is valid or not and removes it if it is invalid.

Detection parameters

  • timeBetweenEvictionRunsMillis
    Idle link detection thread detection cycle, milliseconds. A negative value indicates that the detection thread is not running. The default is -1.

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

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.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
    The number of connections checked each time the idle connection recycler thread (if any) runs, the default is 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
    The minimum time a connection is idle, after which idle connections may be removed. The default is 1000L l.60L30L
  • softMinEvictableIdleTimeMillis
    The minimum time that a connection is idle, after which idle links will be removed and minIdle idle connections will be reserved. The default is -1.
  • evictionPolicyClassName
    The class name of the evict policy is org.Apache.commons.pool2.impl.defaultevictionpolicy by default
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;
    }
}

The two parameters mentioned above are used here.

doc