Class GenericObjectPool<T>

  • Type Parameters:
    T - Type of element pooled in this pool.
    All Implemented Interfaces:
    java.io.Closeable, java.lang.AutoCloseable, GenericObjectPoolMXBean, ObjectPool<T>, UsageTracking<T>

    public class GenericObjectPool<T>
    extends BaseGenericObjectPool<T>
    implements ObjectPool<T>, GenericObjectPoolMXBean, UsageTracking<T>
    A configurable ObjectPool implementation.

    When coupled with the appropriate PooledObjectFactory, GenericObjectPool provides robust pooling functionality for arbitrary objects.

    Optionally, one may configure the pool to examine and possibly evict objects as they sit idle in the pool and to ensure that a minimum number of idle objects are available. This is performed by an "idle object eviction" thread, which runs asynchronously. Caution should be used when configuring this optional feature. Eviction runs contend with client threads for access to objects in the pool, so if they run too frequently performance issues may result.

    The pool can also be configured to detect and remove "abandoned" objects, i.e. objects that have been checked out of the pool but neither used nor returned before the configured removeAbandonedTimeout. Abandoned object removal can be configured to happen when borrowObject is invoked and the pool is close to starvation, or it can be executed by the idle object evictor, or both. If pooled objects implement the TrackedUse interface, their last use will be queried using the getLastUsed method on that interface; otherwise abandonment is determined by how long an object has been checked out from the pool.

    Implementation note: To prevent possible deadlocks, care has been taken to ensure that no call to a factory method will occur within a synchronization block. See POOL-125 and DBCP-44 for more information.

    This class is intended to be thread-safe.

    Since:
    2.0
    See Also:
    GenericKeyedObjectPool
    • Constructor Detail

      • GenericObjectPool

        public GenericObjectPool​(PooledObjectFactory<T> factory)
        Creates a new GenericObjectPool using defaults from GenericObjectPoolConfig.
        Parameters:
        factory - The object factory to be used to create object instances used by this pool
      • GenericObjectPool

        public GenericObjectPool​(PooledObjectFactory<T> factory,
                                 GenericObjectPoolConfig<T> config)
        Creates a new GenericObjectPool using a specific configuration.
        Parameters:
        factory - The object factory to be used to create object instances used by this pool
        config - The configuration to use for this pool instance. The configuration is used by value. Subsequent changes to the configuration object will not be reflected in the pool.
      • GenericObjectPool

        public GenericObjectPool​(PooledObjectFactory<T> factory,
                                 GenericObjectPoolConfig<T> config,
                                 AbandonedConfig abandonedConfig)
        Creates a new GenericObjectPool that tracks and destroys objects that are checked out, but never returned to the pool.
        Parameters:
        factory - The object factory to be used to create object instances used by this pool
        config - The base pool configuration to use for this pool instance. The configuration is used by value. Subsequent changes to the configuration object will not be reflected in the pool.
        abandonedConfig - Configuration for abandoned object identification and removal. The configuration is used by value.
    • Method Detail

      • addObject

        public void addObject()
                       throws java.lang.Exception
        Creates an object, and place it into the pool. addObject() is useful for "pre-loading" a pool with idle objects.

        If there is no capacity available to add to the pool, this is a no-op (no exception, no impact to the pool).

        Specified by:
        addObject in interface ObjectPool<T>
        Throws:
        java.lang.Exception - when PooledObjectFactory.makeObject() fails.
        java.lang.IllegalStateException - after ObjectPool.close() has been called on this pool.
        java.lang.UnsupportedOperationException - when this pool cannot add new idle objects.
      • borrowObject

        public T borrowObject​(java.time.Duration borrowMaxWaitDuration)
                       throws java.lang.Exception
        Borrows an object from the pool using the specific waiting time which only applies if BaseGenericObjectPool.getBlockWhenExhausted() is true.

        If there is one or more idle instance available in the pool, then an idle instance will be selected based on the value of BaseGenericObjectPool.getLifo(), activated and returned. If activation fails, or testOnBorrow is set to true and validation fails, the instance is destroyed and the next available instance is examined. This continues until either a valid instance is returned or there are no more idle instances available.

        If there are no idle instances available in the pool, behavior depends on the maxTotal, (if applicable) BaseGenericObjectPool.getBlockWhenExhausted() and the value passed in to the borrowMaxWaitMillis parameter. If the number of instances checked out from the pool is less than maxTotal, a new instance is created, activated and (if applicable) validated and returned to the caller. If validation fails, a NoSuchElementException is thrown.

        If the pool is exhausted (no available idle instances and no capacity to create new ones), this method will either block (if BaseGenericObjectPool.getBlockWhenExhausted() is true) or throw a NoSuchElementException (if BaseGenericObjectPool.getBlockWhenExhausted() is false). The length of time that this method will block when BaseGenericObjectPool.getBlockWhenExhausted() is true is determined by the value passed in to the borrowMaxWaitMillis parameter.

        When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances to become available. A "fairness" algorithm has been implemented to ensure that threads receive available instances in request arrival order.

        Parameters:
        borrowMaxWaitDuration - The time to wait for an object to become available
        Returns:
        object instance from the pool
        Throws:
        java.util.NoSuchElementException - if an instance cannot be returned
        java.lang.Exception - if an object instance cannot be returned due to an error
        Since:
        2.10.0
      • borrowObject

        public T borrowObject​(long borrowMaxWaitMillis)
                       throws java.lang.Exception
        Borrows an object from the pool using the specific waiting time which only applies if BaseGenericObjectPool.getBlockWhenExhausted() is true.

        If there is one or more idle instance available in the pool, then an idle instance will be selected based on the value of BaseGenericObjectPool.getLifo(), activated and returned. If activation fails, or testOnBorrow is set to true and validation fails, the instance is destroyed and the next available instance is examined. This continues until either a valid instance is returned or there are no more idle instances available.

        If there are no idle instances available in the pool, behavior depends on the maxTotal, (if applicable) BaseGenericObjectPool.getBlockWhenExhausted() and the value passed in to the borrowMaxWaitMillis parameter. If the number of instances checked out from the pool is less than maxTotal, a new instance is created, activated and (if applicable) validated and returned to the caller. If validation fails, a NoSuchElementException is thrown.

        If the pool is exhausted (no available idle instances and no capacity to create new ones), this method will either block (if BaseGenericObjectPool.getBlockWhenExhausted() is true) or throw a NoSuchElementException (if BaseGenericObjectPool.getBlockWhenExhausted() is false). The length of time that this method will block when BaseGenericObjectPool.getBlockWhenExhausted() is true is determined by the value passed in to the borrowMaxWaitMillis parameter.

        When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances to become available. A "fairness" algorithm has been implemented to ensure that threads receive available instances in request arrival order.

        Parameters:
        borrowMaxWaitMillis - The time to wait in milliseconds for an object to become available
        Returns:
        object instance from the pool
        Throws:
        java.util.NoSuchElementException - if an instance cannot be returned
        java.lang.Exception - if an object instance cannot be returned due to an error
      • clear

        public void clear()
        Clears any objects sitting idle in the pool by removing them from the idle instance pool and then invoking the configured PooledObjectFactory.destroyObject(PooledObject) method on each idle instance.

        Implementation notes:

        • This method does not destroy or effect in any way instances that are checked out of the pool when it is invoked.
        • Invoking this method does not prevent objects being returned to the idle instance pool, even during its execution. Additional instances may be returned while removed items are being destroyed.
        • Exceptions encountered destroying idle instances are swallowed but notified via a SwallowedExceptionListener.
        Specified by:
        clear in interface ObjectPool<T>
      • evict

        public void evict()
                   throws java.lang.Exception
        Perform numTests idle object eviction tests, evicting examined objects that meet the criteria for eviction. If testWhileIdle is true, examined objects are validated when visited (and removed if invalid); otherwise only objects that have been idle for more than minEvicableIdleTimeMillis are removed.

        Successive activations of this method examine objects in sequence, cycling through objects in oldest-to-youngest order.

        Specified by:
        evict in class BaseGenericObjectPool<T>
        Throws:
        java.lang.Exception - when there is a problem evicting idle objects.
      • getFactory

        public PooledObjectFactory<T> getFactory()
        Gets a reference to the factory used to create, destroy and validate the objects used by this pool.
        Returns:
        the factory
      • getFactoryType

        public java.lang.String getFactoryType()
        Gets the type - including the specific type rather than the generic - of the factory.
        Specified by:
        getFactoryType in interface GenericObjectPoolMXBean
        Returns:
        A string representation of the factory type
      • getMaxIdle

        public int getMaxIdle()
        Gets the cap on the number of "idle" instances in the pool. If maxIdle is set too low on heavily loaded systems it is possible you will see objects being destroyed and almost immediately new objects being created. This is a result of the active threads momentarily returning objects faster than they are requesting them, causing the number of idle objects to rise above maxIdle. The best value for maxIdle for heavily loaded system will vary but the default is a good starting point.
        Specified by:
        getMaxIdle in interface GenericObjectPoolMXBean
        Returns:
        the maximum number of "idle" instances that can be held in the pool or a negative value if there is no limit
        See Also:
        setMaxIdle(int)
      • getNumActive

        public int getNumActive()
        Description copied from interface: ObjectPool
        Gets the number of instances currently borrowed from this pool. Returns a negative value if this information is not available.
        Specified by:
        getNumActive in interface GenericObjectPoolMXBean
        Specified by:
        getNumActive in interface ObjectPool<T>
        Returns:
        the number of instances currently borrowed from this pool.
      • getNumWaiters

        public int getNumWaiters()
        Gets an estimate of the number of threads currently blocked waiting for an object from the pool. This is intended for monitoring only, not for synchronization control.
        Specified by:
        getNumWaiters in interface GenericObjectPoolMXBean
        Returns:
        The estimate of the number of threads currently blocked waiting for an object from the pool
      • invalidateObject

        public void invalidateObject​(T obj)
                              throws java.lang.Exception
        Invalidates an object from the pool.

        By contract, obj must have been obtained using ObjectPool.borrowObject() or a related method as defined in an implementation or sub-interface.

        This method should be used when an object that has been borrowed is determined (due to an exception or other problem) to be invalid.

        Activation of this method decrements the active count and attempts to destroy the instance, using the default (NORMAL) DestroyMode.

        Specified by:
        invalidateObject in interface ObjectPool<T>
        Parameters:
        obj - a borrowed instance to be disposed.
        Throws:
        java.lang.Exception - if an exception occurs destroying the object
        java.lang.IllegalStateException - if obj does not belong to this pool
      • invalidateObject

        public void invalidateObject​(T obj,
                                     DestroyMode destroyMode)
                              throws java.lang.Exception
        Invalidates an object from the pool, using the provided DestroyMode

        By contract, obj must have been obtained using ObjectPool.borrowObject() or a related method as defined in an implementation or sub-interface.

        This method should be used when an object that has been borrowed is determined (due to an exception or other problem) to be invalid.

        Activation of this method decrements the active count and attempts to destroy the instance, using the provided DestroyMode.

        Specified by:
        invalidateObject in interface ObjectPool<T>
        Parameters:
        obj - a borrowed instance to be disposed.
        destroyMode - destroy activation context provided to the factory
        Throws:
        java.lang.Exception - if an exception occurs destroying the object
        java.lang.IllegalStateException - if obj does not belong to this pool
        Since:
        2.9.0
      • listAllObjects

        public java.util.Set<DefaultPooledObjectInfo> listAllObjects()
        Provides information on all the objects in the pool, both idle (waiting to be borrowed) and active (currently borrowed).

        Note: This is named listAllObjects so it is presented as an operation via JMX. That means it won't be invoked unless the explicitly requested whereas all attributes will be automatically requested when viewing the attributes for an object in a tool like JConsole.

        Specified by:
        listAllObjects in interface GenericObjectPoolMXBean
        Returns:
        Information grouped on all the objects in the pool
      • preparePool

        public void preparePool()
                         throws java.lang.Exception
        Tries to ensure that getMinIdle() idle instances are available in the pool.
        Throws:
        java.lang.Exception - If the associated factory throws an exception
        Since:
        2.4
      • returnObject

        public void returnObject​(T obj)
        Returns an instance to the pool. By contract, obj must have been obtained using ObjectPool.borrowObject() or a related method as defined in an implementation or sub-interface.

        If maxIdle is set to a positive value and the number of idle instances has reached this value, the returning instance is destroyed.

        If testOnReturn == true, the returning instance is validated before being returned to the idle instance pool. In this case, if validation fails, the instance is destroyed.

        Exceptions encountered destroying objects for any reason are swallowed but notified via a SwallowedExceptionListener.

        Specified by:
        returnObject in interface ObjectPool<T>
        Parameters:
        obj - a borrowed instance to be returned.
      • setMaxIdle

        public void setMaxIdle​(int maxIdle)
        Sets the cap on the number of "idle" instances in the pool. If maxIdle is set too low on heavily loaded systems it is possible you will see objects being destroyed and almost immediately new objects being created. This is a result of the active threads momentarily returning objects faster than they are requesting them, causing the number of idle objects to rise above maxIdle. The best value for maxIdle for heavily loaded system will vary but the default is a good starting point.
        Parameters:
        maxIdle - The cap on the number of "idle" instances in the pool. Use a negative value to indicate an unlimited number of idle instances
        See Also:
        getMaxIdle()
      • setMinIdle

        public void setMinIdle​(int minIdle)
        Sets the target for the minimum number of idle objects to maintain in the pool. This setting only has an effect if it is positive and BaseGenericObjectPool.getDurationBetweenEvictionRuns() is greater than zero. If this is the case, an attempt is made to ensure that the pool has the required minimum number of instances during idle object eviction runs.

        If the configured value of minIdle is greater than the configured value for maxIdle then the value of maxIdle will be used instead.

        Parameters:
        minIdle - The minimum number of objects.
        See Also:
        getMinIdle(), getMaxIdle(), BaseGenericObjectPool.getDurationBetweenEvictionRuns()
      • toStringAppendFields

        protected void toStringAppendFields​(java.lang.StringBuilder builder)
        Description copied from class: BaseObject
        Used by sub-classes to include the fields defined by the sub-class in the BaseObject.toString() output.
        Overrides:
        toStringAppendFields in class BaseGenericObjectPool<T>
        Parameters:
        builder - Field names and values are appended to this object
      • use

        public void use​(T pooledObject)
        Description copied from interface: UsageTracking
        Called every time a pooled object is used to enable the pool to better track borrowed objects.
        Specified by:
        use in interface UsageTracking<T>
        Parameters:
        pooledObject - The object that is being used.