Class GenericKeyedObjectPool<K,T>
- java.lang.Object
-
- org.apache.commons.pool2.BaseObject
-
- org.apache.commons.pool2.impl.BaseGenericObjectPool<T>
-
- org.apache.commons.pool2.impl.GenericKeyedObjectPool<K,T>
-
- Type Parameters:
K- The type of keys maintained by this pool.T- Type of element pooled in this pool.
- All Implemented Interfaces:
java.io.Closeable,java.lang.AutoCloseable,GenericKeyedObjectPoolMXBean<K>,KeyedObjectPool<K,T>,UsageTracking<T>
public class GenericKeyedObjectPool<K,T> extends BaseGenericObjectPool<T> implements KeyedObjectPool<K,T>, GenericKeyedObjectPoolMXBean<K>, UsageTracking<T>
A configurableKeyedObjectPoolimplementation.When coupled with the appropriate
KeyedPooledObjectFactory,GenericKeyedObjectPoolprovides robust pooling functionality for keyed objects. AGenericKeyedObjectPoolcan be viewed as a map of sub-pools, keyed on the (unique) key values provided to thepreparePool,addObjectorborrowObjectmethods. Each time a new key value is provided to one of these methods, a sub-new pool is created under the given key to be managed by the containingGenericKeyedObjectPool.Note that the current implementation uses a ConcurrentHashMap which uses equals() to compare keys. This means that distinct instance keys must be distinguishable using equals.
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 is maintained for each key. 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.
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:
GenericObjectPool
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classGenericKeyedObjectPool.ObjectDeque<S>Maintains information on the per key queue for a given key.-
Nested classes/interfaces inherited from class org.apache.commons.pool2.impl.BaseGenericObjectPool
BaseGenericObjectPool.EvictionIterator, BaseGenericObjectPool.Evictor, BaseGenericObjectPool.IdentityWrapper<T>
-
-
Field Summary
Fields Modifier and Type Field Description private KevictionKeyprivate java.util.Iterator<K>evictionKeyIteratorprivate KeyedPooledObjectFactory<K,T>factoryprivate booleanfairnessprivate java.util.concurrent.locks.ReadWriteLockkeyLockprivate intmaxIdlePerKeyprivate intmaxTotalPerKeyprivate intminIdlePerKeyprivate java.util.concurrent.atomic.AtomicIntegernumTotalprivate static java.lang.StringONAME_BASEprivate java.util.ArrayList<K>poolKeyListprivate java.util.concurrent.ConcurrentHashMap<K,GenericKeyedObjectPool.ObjectDeque<T>>poolMapprivate booleanreuseCapacityOnMaintenanceprivate booleanreuseCapacityOnReturnprivate static java.lang.IntegerZERO-
Fields inherited from class org.apache.commons.pool2.impl.BaseGenericObjectPool
abandonedConfig, closed, closeLock, createdCount, destroyedByBorrowValidationCount, destroyedByEvictorCount, destroyedCount, evictionIterator, evictionLock, MEAN_TIMING_STATS_CACHE_SIZE
-
-
Constructor Summary
Constructors Constructor Description GenericKeyedObjectPool(KeyedPooledObjectFactory<K,T> factory)Constructs a newGenericKeyedObjectPoolusing defaults fromGenericKeyedObjectPoolConfig.GenericKeyedObjectPool(KeyedPooledObjectFactory<K,T> factory, GenericKeyedObjectPoolConfig<T> config)Constructs a newGenericKeyedObjectPoolusing a specific configuration.GenericKeyedObjectPool(KeyedPooledObjectFactory<K,T> factory, GenericKeyedObjectPoolConfig<T> config, AbandonedConfig abandonedConfig)Creates a newGenericKeyedObjectPoolthat tracks and destroys objects that are checked out, but never returned to the pool.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description private voidaddIdleObject(K key, PooledObject<T> p)Add an object to the set of idle objects for a given key.voidaddObject(K key)Create an object using thefactory, passivate it, and then place it in the idle object pool.TborrowObject(K key)Equivalent to.borrowObject(key,BaseGenericObjectPool.getMaxWaitDuration())TborrowObject(K key, long maxWaitMillis)Borrows an object from the sub-pool associated with the given key using the specified waiting time which only applies ifBaseGenericObjectPool.getBlockWhenExhausted()is true.TborrowObject(K key, java.time.Duration maxWaitDuration)Borrows an object from the sub-pool associated with the given key using the specified waiting time which only applies ifBaseGenericObjectPool.getBlockWhenExhausted()is true.private intcalculateDeficit(GenericKeyedObjectPool.ObjectDeque<T> objectDeque)Calculate the number of objects that need to be created to attempt to maintain the minimum number of idle objects while not exceeded the limits on the maximum number of objects either per key or totally.voidclear()Clears any objects sitting idle in the pool by removing them from the idle instance sub-pools and then invoking the configured PoolableObjectFactory'sKeyedPooledObjectFactory.destroyObject(Object, PooledObject)method on each idle instance.voidclear(K key)Clears the specified sub-pool, removing all pooled instances corresponding to the givenkey.voidclear(K key, boolean reuseCapacity)Clears the specified sub-pool, removing all pooled instances corresponding to the givenkey.voidclearOldest()Clears oldest 15% of objects in pool.voidclose()Closes the keyed object pool.private PooledObject<T>create(K key, java.time.Duration maxWaitDuration)Creates a new pooled object or null.private voidderegister(K k)De-register the use of a key by an object.private booleandestroy(K key, PooledObject<T> toDestroy, boolean always, DestroyMode destroyMode)Destroy the wrapped, pooled object.(package private) voidensureMinIdle()Tries to ensure that the configured minimum number of idle instances are available in the pool.private voidensureMinIdle(K key)Try to ensure that the configured number of minimum idle objects is available in the pool for the given key.voidevict()PerformnumTestsidle object eviction tests, evicting examined objects that meet the criteria for eviction.KeyedPooledObjectFactory<K,T>getFactory()Gets a reference to the factory used to create, destroy and validate the objects used by this pool.java.util.List<K>getKeys()Gets a copy of the pool key list.intgetMaxIdlePerKey()Gets the cap on the number of "idle" instances per key in the pool.intgetMaxTotalPerKey()Gets the limit on the number of object instances allocated by the pool (checked out or idle), per key.intgetMinIdlePerKey()Gets the target for the minimum number of idle objects to maintain in each of the keyed sub-pools.intgetNumActive()Gets the total number of instances currently borrowed from this pool but not yet returned.intgetNumActive(K key)Gets the number of instances currently borrowed from but not yet returned to the pool corresponding to the givenkey.java.util.Map<java.lang.String,java.lang.Integer>getNumActivePerKey()SeegetNumActivePerKey().intgetNumIdle()Gets the number of instances currently idle in this pool.intgetNumIdle(K key)Gets the number of instances corresponding to the givenkeycurrently idle in this pool.private intgetNumTests()Gets the number of objects to test in a run of the idle object evictor.intgetNumWaiters()Gets an estimate of the number of threads currently blocked waiting for an object from the pool.java.util.Map<java.lang.String,java.lang.Integer>getNumWaitersByKey()Gets an estimate of the number of threads currently blocked waiting for an object from the pool for each key.booleangetReuseCapacityOnMaintenance()Gets whether to callreuseCapacity()during pool maintenance (eviction).booleangetReuseCapacityOnReturn()Gets whether to callreuseCapacity()when returning objects to the pool.(package private) java.lang.StringgetStatsString()Gets a statistics string.private booleanhasBorrowWaiters()Tests to see if there are any threads currently waiting to borrow objects but are blocked waiting for more objects to become available.voidinvalidateObject(K key, T obj)Invalidates an object from the pool.voidinvalidateObject(K key, T obj, DestroyMode destroyMode)Invalidates an object from the pool, using the providedDestroyMode.java.util.Map<java.lang.String,java.util.List<DefaultPooledObjectInfo>>listAllObjects()Provides information on all the objects in the pool, both idle (waiting to be borrowed) and active (currently borrowed).voidpreparePool(K key)Registers a key for pool control and ensures thatgetMinIdlePerKey()idle instances are created.private GenericKeyedObjectPool.ObjectDeque<T>register(K k)Register the use of a key by an object.private voidremoveAbandoned(AbandonedConfig abandonedConfig)Recovers abandoned objects which have been checked out but not used since longer than the removeAbandonedTimeout.voidreturnObject(K key, T obj)Returns an object to a keyed sub-pool.private voidreuseCapacity()Attempt to create one new instance to serve from the most heavily loaded pool that can add a new instance.private voidreuseCapacity(int newCapacity)CallreuseCapacity()repeatedly.voidsetConfig(GenericKeyedObjectPoolConfig<T> conf)Sets the configuration.voidsetMaxIdlePerKey(int maxIdlePerKey)Sets the cap on the number of "idle" instances per key in the pool.voidsetMaxTotalPerKey(int maxTotalPerKey)Sets the limit on the number of object instances allocated by the pool (checked out or idle), per key.voidsetMinIdlePerKey(int minIdlePerKey)Sets the target for the minimum number of idle objects to maintain in each of the keyed sub-pools.voidsetReuseCapacityOnMaintenance(boolean reuseCapacityOnMaintenance)Sets whether to callreuseCapacity()during pool maintenance (eviction).voidsetReuseCapacityOnReturn(boolean reuseCapacityOnReturn)Sets whether to callreuseCapacity()when returning objects to the pool.protected voidtoStringAppendFields(java.lang.StringBuilder builder)Used by sub-classes to include the fields defined by the sub-class in theBaseObject.toString()output.voiduse(T pooledObject)Called every time a pooled object is used to enable the pool to better track borrowed objects.private voidwhenWaitersAddObject(K key, LinkedBlockingDeque<PooledObject<T>> idleObjects)When there is at least one thread waiting on the given deque, try to add an instance to pool under the given key.-
Methods inherited from class org.apache.commons.pool2.impl.BaseGenericObjectPool
appendStats, assertOpen, createRemoveList, durationSince, getBlockWhenExhausted, getBorrowedCount, getCollectDetailedStatistics, getCreatedCount, getCreationStackTrace, getDestroyedByBorrowValidationCount, getDestroyedByEvictorCount, getDestroyedCount, getDurationBetweenEvictionRuns, getEvictionPolicy, getEvictionPolicyClassName, getEvictorShutdownTimeout, getEvictorShutdownTimeoutDuration, getEvictorShutdownTimeoutMillis, getFairness, getJmxName, getLifo, getLogAbandoned, getMaxBorrowWaitDuration, getMaxBorrowWaitTimeMillis, getMaxTotal, getMaxWaitDuration, getMaxWaitMillis, getMeanActiveDuration, getMeanActiveTimeMillis, getMeanBorrowWaitDuration, getMeanBorrowWaitTimeMillis, getMeanIdleDuration, getMeanIdleTimeMillis, getMessageStatistics, getMinEvictableIdleDuration, getMinEvictableIdleTime, getMinEvictableIdleTimeMillis, getNumTestsPerEvictionRun, getRemoveAbandonedOnBorrow, getRemoveAbandonedOnMaintenance, getRemoveAbandonedTimeout, getRemoveAbandonedTimeoutDuration, getReturnedCount, getSoftMinEvictableIdleDuration, getSoftMinEvictableIdleTime, getSoftMinEvictableIdleTimeMillis, getSwallowedExceptionListener, getTestOnBorrow, getTestOnCreate, getTestOnReturn, getTestWhileIdle, getTimeBetweenEvictionRuns, getTimeBetweenEvictionRunsMillis, isAbandonedConfig, isClosed, jmxUnregister, markReturningState, setAbandonedConfig, setBlockWhenExhausted, setCollectDetailedStatistics, setConfig, setDurationBetweenEvictionRuns, setEvictionPolicy, setEvictionPolicyClassName, setEvictionPolicyClassName, setEvictorShutdownTimeout, setEvictorShutdownTimeoutMillis, setLifo, setMaxTotal, setMaxWait, setMaxWaitMillis, setMessagesStatistics, setMinEvictableIdle, setMinEvictableIdleDuration, setMinEvictableIdleTime, setMinEvictableIdleTimeMillis, setNumTestsPerEvictionRun, setSoftMinEvictableIdle, setSoftMinEvictableIdleDuration, setSoftMinEvictableIdleTime, setSoftMinEvictableIdleTimeMillis, setSwallowedExceptionListener, setTestOnBorrow, setTestOnCreate, setTestOnReturn, setTestWhileIdle, setTimeBetweenEvictionRuns, setTimeBetweenEvictionRunsMillis, startEvictor, stopEvictor, swallowException, updateStatsBorrow, updateStatsReturn, wait
-
Methods inherited from class org.apache.commons.pool2.BaseObject
toString
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean
getBlockWhenExhausted, getBorrowedCount, getCreatedCount, getCreationStackTrace, getDestroyedByBorrowValidationCount, getDestroyedByEvictorCount, getDestroyedCount, getFairness, getLifo, getLogAbandoned, getMaxBorrowWaitTimeMillis, getMaxTotal, getMaxWaitMillis, getMeanActiveTimeMillis, getMeanBorrowWaitTimeMillis, getMeanIdleTimeMillis, getMinEvictableIdleTimeMillis, getNumTestsPerEvictionRun, getRemoveAbandonedOnBorrow, getRemoveAbandonedOnMaintenance, getRemoveAbandonedTimeout, getReturnedCount, getTestOnBorrow, getTestOnCreate, getTestOnReturn, getTestWhileIdle, getTimeBetweenEvictionRunsMillis, isAbandonedConfig, isClosed
-
Methods inherited from interface org.apache.commons.pool2.KeyedObjectPool
addObjects, addObjects
-
-
-
-
Field Detail
-
ZERO
private static final java.lang.Integer ZERO
-
ONAME_BASE
private static final java.lang.String ONAME_BASE
- See Also:
- Constant Field Values
-
maxIdlePerKey
private volatile int maxIdlePerKey
-
minIdlePerKey
private volatile int minIdlePerKey
-
maxTotalPerKey
private volatile int maxTotalPerKey
-
reuseCapacityOnReturn
private volatile boolean reuseCapacityOnReturn
-
reuseCapacityOnMaintenance
private volatile boolean reuseCapacityOnMaintenance
-
factory
private final KeyedPooledObjectFactory<K,T> factory
-
fairness
private final boolean fairness
-
poolMap
private final java.util.concurrent.ConcurrentHashMap<K,GenericKeyedObjectPool.ObjectDeque<T>> poolMap
-
poolKeyList
private final java.util.ArrayList<K> poolKeyList
-
keyLock
private final java.util.concurrent.locks.ReadWriteLock keyLock
-
numTotal
private final java.util.concurrent.atomic.AtomicInteger numTotal
-
evictionKeyIterator
private java.util.Iterator<K> evictionKeyIterator
-
evictionKey
private K evictionKey
-
-
Constructor Detail
-
GenericKeyedObjectPool
public GenericKeyedObjectPool(KeyedPooledObjectFactory<K,T> factory)
Constructs a newGenericKeyedObjectPoolusing defaults fromGenericKeyedObjectPoolConfig.- Parameters:
factory- the factory to be used to create entries
-
GenericKeyedObjectPool
public GenericKeyedObjectPool(KeyedPooledObjectFactory<K,T> factory, GenericKeyedObjectPoolConfig<T> config)
Constructs a newGenericKeyedObjectPoolusing a specific configuration.- Parameters:
factory- the factory to be used to create entriesconfig- 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.
-
GenericKeyedObjectPool
public GenericKeyedObjectPool(KeyedPooledObjectFactory<K,T> factory, GenericKeyedObjectPoolConfig<T> config, AbandonedConfig abandonedConfig)
Creates a newGenericKeyedObjectPoolthat 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 poolconfig- 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.- Since:
- 2.10.0
-
-
Method Detail
-
addIdleObject
private void addIdleObject(K key, PooledObject<T> p) throws java.lang.Exception
Add an object to the set of idle objects for a given key. If the object is null this is a no-op.- Parameters:
key- The key to associate with the idle objectp- The wrapped object to add.- Throws:
java.lang.Exception- If the associated factory fails to passivate the object
-
addObject
public void addObject(K key) throws java.lang.Exception
Create an object using thefactory, passivate it, and then place it in the idle object pool.addObjectis useful for "pre-loading" a pool with idle objects.If there is no capacity available to add to the pool under the given key, this is a no-op (no exception, no impact to the pool).
If the factory returns null when creating an instance, a
NullPointerExceptionis thrown.- Specified by:
addObjectin interfaceKeyedObjectPool<K,T>- Parameters:
key- the key a new instance should be added to- Throws:
java.lang.Exception- whenKeyedPooledObjectFactory.makeObject(K)fails.
-
borrowObject
public T borrowObject(K key) throws java.lang.Exception
Equivalent to. Borrows an instance from this pool for the specifiedborrowObject(key,BaseGenericObjectPool.getMaxWaitDuration())key.Instances returned from this method will have been either newly created with
makeObjector will be a previously idle object and have been activated withactivateObjectand then (optionally) validated withvalidateObject.By contract, clients must return the borrowed object using
returnObject,invalidateObject, or a related method as defined in an implementation or sub-interface, using akeythat isequivalentto the one used to borrow the instance in the first place.The behavior of this method when the pool has been exhausted is not strictly specified (although it may be specified by implementations).
- Specified by:
borrowObjectin interfaceKeyedObjectPool<K,T>- Parameters:
key- the key used to obtain the object- Returns:
- an instance from this pool.
- Throws:
java.lang.IllegalStateException- afterclosehas been called on this pooljava.lang.Exception- whenmakeObjectthrows an exceptionjava.util.NoSuchElementException- when the pool is exhausted and cannot or will not return another instance
-
borrowObject
public T borrowObject(K key, java.time.Duration maxWaitDuration) throws java.lang.Exception
Borrows an object from the sub-pool associated with the given key using the specified waiting time which only applies ifBaseGenericObjectPool.getBlockWhenExhausted()is true.If there is one or more idle instances available in the sub-pool associated with the given key, then an idle instance will be selected based on the value of
BaseGenericObjectPool.getLifo(), activated and returned. If activation fails, ortestOnBorrowis set totrueand 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 sub-pool associated with the given key, behavior depends on the
maxTotalPerKey,maxTotal, and (if applicable)BaseGenericObjectPool.getBlockWhenExhausted()and the value passed in to theborrowMaxWaitMillisparameter. If the number of instances checked out from the sub-pool under the given key is less thanmaxTotalPerKeyand the total number of instances in circulation (under all keys) is less thanmaxTotal, a new instance is created, activated and (if applicable) validated and returned to the caller. If validation fails, aNoSuchElementExceptionwill be thrown. If the factory returns null when creating an instance, aNullPointerExceptionis thrown.If the associated sub-pool is exhausted (no available idle instances and no capacity to create new ones), this method will either block (
BaseGenericObjectPool.getBlockWhenExhausted()is true) or throw aNoSuchElementException(BaseGenericObjectPool.getBlockWhenExhausted()is false). The length of time that this method will block whenBaseGenericObjectPool.getBlockWhenExhausted()is true is determined by the value passed in to theborrowMaxWaitparameter.When
maxTotalis set to a positive value and this method is invoked when at the limit with no idle instances available under the requested key, an attempt is made to create room by clearing the oldest 15% of the elements from the keyed sub-pools.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:
key- pool keymaxWaitDuration- The time to wait for an object to become available- Returns:
- object instance from the keyed pool
- Throws:
java.util.NoSuchElementException- if a keyed object instance cannot be returned because the pool is exhausted.java.lang.Exception- if a keyed object instance cannot be returned due to an error- Since:
- 2.12.2
-
borrowObject
public T borrowObject(K key, long maxWaitMillis) throws java.lang.Exception
Borrows an object from the sub-pool associated with the given key using the specified waiting time which only applies ifBaseGenericObjectPool.getBlockWhenExhausted()is true.If there is one or more idle instances available in the sub-pool associated with the given key, then an idle instance will be selected based on the value of
BaseGenericObjectPool.getLifo(), activated and returned. If activation fails, ortestOnBorrowis set totrueand 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 sub-pool associated with the given key, behavior depends on the
maxTotalPerKey,maxTotal, and (if applicable)BaseGenericObjectPool.getBlockWhenExhausted()and the value passed in to theborrowMaxWaitMillisparameter. If the number of instances checked out from the sub-pool under the given key is less thanmaxTotalPerKeyand the total number of instances in circulation (under all keys) is less thanmaxTotal, a new instance is created, activated and (if applicable) validated and returned to the caller. If validation fails, aNoSuchElementExceptionwill be thrown. If the factory returns null when creating an instance, aNullPointerExceptionis thrown.If the associated sub-pool is exhausted (no available idle instances and no capacity to create new ones), this method will either block (
BaseGenericObjectPool.getBlockWhenExhausted()is true) or throw aNoSuchElementException(BaseGenericObjectPool.getBlockWhenExhausted()is false). The length of time that this method will block whenBaseGenericObjectPool.getBlockWhenExhausted()is true is determined by the value passed in to theborrowMaxWaitparameter.When
maxTotalis set to a positive value and this method is invoked when at the limit with no idle instances available under the requested key, an attempt is made to create room by clearing the oldest 15% of the elements from the keyed sub-pools.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:
key- pool keymaxWaitMillis- The time to wait in milliseconds for an object to become available- Returns:
- object instance from the keyed pool
- Throws:
java.util.NoSuchElementException- if a keyed object instance cannot be returned because the pool is exhausted.java.lang.Exception- if a keyed object instance cannot be returned due to an error
-
calculateDeficit
private int calculateDeficit(GenericKeyedObjectPool.ObjectDeque<T> objectDeque)
Calculate the number of objects that need to be created to attempt to maintain the minimum number of idle objects while not exceeded the limits on the maximum number of objects either per key or totally.- Parameters:
objectDeque- The set of objects to check- Returns:
- The number of new objects to create
-
clear
public void clear()
Clears any objects sitting idle in the pool by removing them from the idle instance sub-pools and then invoking the configured PoolableObjectFactory'sKeyedPooledObjectFactory.destroyObject(Object, PooledObject)method on each idle instance.Implementation notes:
- This method does not destroy or effect in any way instances that are checked out 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:
clearin interfaceKeyedObjectPool<K,T>
-
clear
public void clear(K key)
Clears the specified sub-pool, removing all pooled instances corresponding to the givenkey. Exceptions encountered destroying idle instances are swallowed but notified via aSwallowedExceptionListener.If there are clients waiting to borrow objects, this method will attempt to reuse the capacity freed by this operation, adding instances to the most loaded keyed pools. To avoid triggering possible object creation, use
clear(Object, boolean).- Specified by:
clearin interfaceKeyedObjectPool<K,T>- Parameters:
key- the key to clear
-
clear
public void clear(K key, boolean reuseCapacity)
Clears the specified sub-pool, removing all pooled instances corresponding to the givenkey. Exceptions encountered destroying idle instances are swallowed but notified via aSwallowedExceptionListener.If reuseCapacity is true and there are clients waiting to borrow objects, this method will attempt to reuse the capacity freed by this operation, adding instances to the most loaded keyed pools.
- Parameters:
key- the key to clearreuseCapacity- whether or not to reuse freed capacity- Since:
- 2.12.0
-
clearOldest
public void clearOldest()
Clears oldest 15% of objects in pool. The method sorts the objects into a TreeMap and then iterates the first 15% for removal.
-
close
public void close()
Closes the keyed object pool. Once the pool is closed,borrowObject(Object)will fail with IllegalStateException, butreturnObject(Object, Object)andinvalidateObject(Object, Object)will continue to work, with returned objects destroyed on return.Destroys idle instances in the pool by invoking
clear().- Specified by:
closein interfacejava.lang.AutoCloseable- Specified by:
closein interfacejava.io.Closeable- Specified by:
closein interfaceKeyedObjectPool<K,T>- Specified by:
closein classBaseGenericObjectPool<T>
-
create
private PooledObject<T> create(K key, java.time.Duration maxWaitDuration) throws java.lang.Exception
Creates a new pooled object or null.- Parameters:
key- Key associated with new pooled object.maxWaitDuration- The time to wait in this method. If negative or ZERO, this method may wait indefinitely.- Returns:
- The new, wrapped pooled object. May return null.
- Throws:
java.lang.Exception- If the objection creation fails.
-
deregister
private void deregister(K k)
De-register the use of a key by an object.register(Object)andderegister(Object)must always be used as a pair.- Parameters:
k- The key to de-register
-
destroy
private boolean destroy(K key, PooledObject<T> toDestroy, boolean always, DestroyMode destroyMode) throws java.lang.Exception
Destroy the wrapped, pooled object.- Parameters:
key- The key associated with the object to destroytoDestroy- The wrapped object to be destroyedalways- Should the object be destroyed even if it is not currently in the set of idle objects for the given keydestroyMode-DestroyModecontext provided to the factory- Returns:
trueif the object was destroyed, otherwisefalse- Throws:
java.lang.Exception- If the factory throws an exception during destruction
-
ensureMinIdle
void ensureMinIdle() throws java.lang.ExceptionDescription copied from class:BaseGenericObjectPoolTries to ensure that the configured minimum number of idle instances are available in the pool.- Specified by:
ensureMinIdlein classBaseGenericObjectPool<T>- Throws:
java.lang.Exception- if an error occurs creating idle instances
-
ensureMinIdle
private void ensureMinIdle(K key) throws java.lang.Exception
Try to ensure that the configured number of minimum idle objects is available in the pool for the given key.If there is no capacity available to add to the pool, this is a no-op (no exception, no impact to the pool).
If the factory returns null when creating an object, a
NullPointerExceptionis thrown.- Parameters:
key- The key to check for idle objects- Throws:
java.lang.Exception- If a new object is required and cannot be created
-
evict
public void evict() throws java.lang.ExceptionPerformnumTestsidle object eviction tests, evicting examined objects that meet the criteria for eviction. IftestWhileIdleis true, examined objects are validated when visited (and removed if invalid); otherwise only objects that have been idle for more thanminEvicableIdleTimeMillisare removed.Successive activations of this method examine objects in keyed sub-pools in sequence, cycling through the keys and examining objects in oldest-to-youngest order within the keyed sub-pools.
- Specified by:
evictin classBaseGenericObjectPool<T>- Throws:
java.lang.Exception- when there is a problem evicting idle objects.
-
getFactory
public KeyedPooledObjectFactory<K,T> getFactory()
Gets a reference to the factory used to create, destroy and validate the objects used by this pool.- Returns:
- the factory
-
getKeys
public java.util.List<K> getKeys()
Gets a copy of the pool key list.- Specified by:
getKeysin interfaceKeyedObjectPool<K,T>- Returns:
- a copy of the pool key list.
- Since:
- 2.12.0
-
getMaxIdlePerKey
public int getMaxIdlePerKey()
Gets the cap on the number of "idle" instances per key in the pool. If maxIdlePerKey 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 maxIdlePerKey. The best value for maxIdlePerKey for heavily loaded system will vary but the default is a good starting point.- Specified by:
getMaxIdlePerKeyin interfaceGenericKeyedObjectPoolMXBean<K>- Returns:
- the maximum number of "idle" instances that can be held in a given keyed sub-pool or a negative value if there is no limit
- See Also:
setMaxIdlePerKey(int)
-
getMaxTotalPerKey
public int getMaxTotalPerKey()
Gets the limit on the number of object instances allocated by the pool (checked out or idle), per key. When the limit is reached, the sub-pool is said to be exhausted. A negative value indicates no limit.- Specified by:
getMaxTotalPerKeyin interfaceGenericKeyedObjectPoolMXBean<K>- Returns:
- the limit on the number of active instances per key
- See Also:
setMaxTotalPerKey(int)
-
getMinIdlePerKey
public int getMinIdlePerKey()
Gets the target for the minimum number of idle objects to maintain in each of the keyed sub-pools. This setting only has an effect if it is positive andBaseGenericObjectPool.getDurationBetweenEvictionRuns()is greater than zero. If this is the case, an attempt is made to ensure that each sub-pool has the required minimum number of instances during idle object eviction runs.If the configured value of minIdlePerKey is greater than the configured value for maxIdlePerKey then the value of maxIdlePerKey will be used instead.
- Specified by:
getMinIdlePerKeyin interfaceGenericKeyedObjectPoolMXBean<K>- Returns:
- minimum size of the each keyed pool
- See Also:
BaseGenericObjectPool.setTimeBetweenEvictionRunsMillis(long)
-
getNumActive
public int getNumActive()
Description copied from interface:KeyedObjectPoolGets the total number of instances currently borrowed from this pool but not yet returned. Returns a negative value if this information is not available.- Specified by:
getNumActivein interfaceGenericKeyedObjectPoolMXBean<K>- Specified by:
getNumActivein interfaceKeyedObjectPool<K,T>- Returns:
- the total number of instances currently borrowed from this pool but not yet returned.
-
getNumActive
public int getNumActive(K key)
Description copied from interface:KeyedObjectPoolGets the number of instances currently borrowed from but not yet returned to the pool corresponding to the givenkey. Returns a negative value if this information is not available.- Specified by:
getNumActivein interfaceKeyedObjectPool<K,T>- Parameters:
key- the key to query- Returns:
- the number of instances currently borrowed from but not yet
returned to the pool corresponding to the given
key.
-
getNumActivePerKey
public java.util.Map<java.lang.String,java.lang.Integer> getNumActivePerKey()
Description copied from interface:GenericKeyedObjectPoolMXBeanSeegetNumActivePerKey().- Specified by:
getNumActivePerKeyin interfaceGenericKeyedObjectPoolMXBean<K>- Returns:
- See
getNumActivePerKey().
-
getNumIdle
public int getNumIdle()
Description copied from class:BaseGenericObjectPoolGets the number of instances currently idle in this pool.- Specified by:
getNumIdlein interfaceGenericKeyedObjectPoolMXBean<K>- Specified by:
getNumIdlein interfaceKeyedObjectPool<K,T>- Specified by:
getNumIdlein classBaseGenericObjectPool<T>- Returns:
- count of instances available for checkout from the pool
-
getNumIdle
public int getNumIdle(K key)
Description copied from interface:KeyedObjectPoolGets the number of instances corresponding to the givenkeycurrently idle in this pool. Returns a negative value if this information is not available.- Specified by:
getNumIdlein interfaceKeyedObjectPool<K,T>- Parameters:
key- the key to query- Returns:
- the number of instances corresponding to the given
keycurrently idle in this pool.
-
getNumTests
private int getNumTests()
Gets the number of objects to test in a run of the idle object evictor.- Returns:
- The number of objects to test for validity
-
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:
getNumWaitersin interfaceGenericKeyedObjectPoolMXBean<K>- Returns:
- The estimate of the number of threads currently blocked waiting for an object from the pool
-
getNumWaitersByKey
public java.util.Map<java.lang.String,java.lang.Integer> getNumWaitersByKey()
Gets an estimate of the number of threads currently blocked waiting for an object from the pool for each key. This is intended for monitoring only, not for synchronization control.- Specified by:
getNumWaitersByKeyin interfaceGenericKeyedObjectPoolMXBean<K>- Returns:
- The estimate of the number of threads currently blocked waiting for an object from the pool for each key
-
getReuseCapacityOnMaintenance
public boolean getReuseCapacityOnMaintenance()
Gets whether to callreuseCapacity()during pool maintenance (eviction). When true, the pool will attempt to reuse freed capacity at the end of each eviction run.- Returns:
trueif capacity reuse is enabled during maintenance,falseotherwise- Since:
- 2.13.0
- See Also:
setReuseCapacityOnMaintenance(boolean)
-
getReuseCapacityOnReturn
public boolean getReuseCapacityOnReturn()
Gets whether to callreuseCapacity()when returning objects to the pool. When true, the pool will check if there are threads waiting to borrow objects and attempt to reuse the capacity freed by the return operation.- Returns:
trueif capacity reuse is enabled on return,falseotherwise- Since:
- 2.13.0
- See Also:
setReuseCapacityOnReturn(boolean)
-
getStatsString
java.lang.String getStatsString()
Description copied from class:BaseGenericObjectPoolGets a statistics string.- Overrides:
getStatsStringin classBaseGenericObjectPool<T>- Returns:
- a statistics string.
-
hasBorrowWaiters
private boolean hasBorrowWaiters()
Tests to see if there are any threads currently waiting to borrow objects but are blocked waiting for more objects to become available.- Returns:
trueif there is at least one thread waiting otherwisefalse
-
invalidateObject
public void invalidateObject(K key, T obj) throws java.lang.Exception
Invalidates an object from the pool.By contract,
objmust have been obtained usingborrowObjector a related method as defined in an implementation or sub-interface using akeythat is equivalent to the one used to borrow theObjectin the first place.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 associated with the given keyed pool and attempts to destroy
obj.- Specified by:
invalidateObjectin interfaceKeyedObjectPool<K,T>- Parameters:
key- pool keyobj- instance to invalidate- Throws:
java.lang.Exception- if an exception occurs destroying the objectjava.lang.IllegalStateException- if obj does not belong to the pool under the given key
-
invalidateObject
public void invalidateObject(K key, T obj, DestroyMode destroyMode) throws java.lang.Exception
Invalidates an object from the pool, using the providedDestroyMode.By contract,
objmust have been obtained usingborrowObjector a related method as defined in an implementation or sub-interface using akeythat is equivalent to the one used to borrow theObjectin the first place.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 associated with the given keyed pool and attempts to destroy
obj.- Specified by:
invalidateObjectin interfaceKeyedObjectPool<K,T>- Parameters:
key- pool keyobj- instance to invalidatedestroyMode- DestroyMode context provided to factory- Throws:
java.lang.Exception- if an exception occurs destroying the objectjava.lang.IllegalStateException- if obj does not belong to the pool under the given key- Since:
- 2.9.0
-
listAllObjects
public java.util.Map<java.lang.String,java.util.List<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 explicitly requested whereas all attributes will be automatically requested when viewing the attributes for an object in a tool like JConsole.
- Specified by:
listAllObjectsin interfaceGenericKeyedObjectPoolMXBean<K>- Returns:
- Information grouped by key on all the objects in the pool
-
preparePool
public void preparePool(K key) throws java.lang.Exception
Registers a key for pool control and ensures thatgetMinIdlePerKey()idle instances are created.- Parameters:
key- The key to register for pool control.- Throws:
java.lang.Exception- If the associated factory throws an exception
-
register
private GenericKeyedObjectPool.ObjectDeque<T> register(K k)
Register the use of a key by an object.register(Object)andderegister(Object)must always be used as a pair.- Parameters:
k- The key to register- Returns:
- The objects currently associated with the given key. If this method returns without throwing an exception then it will never return null.
-
removeAbandoned
private void removeAbandoned(AbandonedConfig abandonedConfig)
Recovers abandoned objects which have been checked out but not used since longer than the removeAbandonedTimeout.- Parameters:
abandonedConfig- The configuration to use to identify abandoned objects
-
returnObject
public void returnObject(K key, T obj)
Returns an object to a keyed sub-pool.If
maxIdleis set to a positive value and the number of idle instances under the given key has reached this value, the returning instance is destroyed.If
testOnReturn== true, the returning instance is validated before being returned to the idle instance sub-pool under the given key. 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:
returnObjectin interfaceKeyedObjectPool<K,T>- Parameters:
key- pool keyobj- instance to return to the keyed pool- Throws:
java.lang.IllegalStateException- if an object is returned to the pool that was not borrowed from it or if an object is returned to the pool multiple times
-
reuseCapacity
private void reuseCapacity()
Attempt to create one new instance to serve from the most heavily loaded pool that can add a new instance. This method exists to ensure liveness in the pool when threads are parked waiting and capacity to create instances under the requested keys subsequently becomes available. This method is not guaranteed to create an instance and its selection of the most loaded pool that can create an instance may not always be correct, since it does not lock the pool and instances may be created, borrowed, returned or destroyed by other threads while it is executing.
-
reuseCapacity
private void reuseCapacity(int newCapacity)
CallreuseCapacity()repeatedly.Always activates
reuseCapacity()at least once.- Parameters:
newCapacity- number of times to callreuseCapacity()
-
setConfig
public void setConfig(GenericKeyedObjectPoolConfig<T> conf)
Sets the configuration.- Parameters:
conf- the new configuration to use. This is used by value.- See Also:
GenericKeyedObjectPoolConfig
-
setMaxIdlePerKey
public void setMaxIdlePerKey(int maxIdlePerKey)
Sets the cap on the number of "idle" instances per key in the pool. If maxIdlePerKey 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 maxIdlePerKey. The best value for maxIdlePerKey for heavily loaded system will vary but the default is a good starting point.- Parameters:
maxIdlePerKey- the maximum number of "idle" instances that can be held in a given keyed sub-pool. Use a negative value for no limit- See Also:
getMaxIdlePerKey()
-
setMaxTotalPerKey
public void setMaxTotalPerKey(int maxTotalPerKey)
Sets the limit on the number of object instances allocated by the pool (checked out or idle), per key. When the limit is reached, the sub-pool is said to be exhausted. A negative value indicates no limit.- Parameters:
maxTotalPerKey- the limit on the number of active instances per key- See Also:
getMaxTotalPerKey()
-
setMinIdlePerKey
public void setMinIdlePerKey(int minIdlePerKey)
Sets the target for the minimum number of idle objects to maintain in each of the keyed sub-pools. This setting only has an effect if it is positive andBaseGenericObjectPool.getDurationBetweenEvictionRuns()is greater than zero. If this is the case, an attempt is made to ensure that each sub-pool has the required minimum number of instances during idle object eviction runs.If the configured value of minIdlePerKey is greater than the configured value for maxIdlePerKey then the value of maxIdlePerKey will be used instead.
- Parameters:
minIdlePerKey- The minimum size of the each keyed pool- See Also:
getMinIdlePerKey(),getMaxIdlePerKey(),BaseGenericObjectPool.setDurationBetweenEvictionRuns(Duration)
-
setReuseCapacityOnMaintenance
public void setReuseCapacityOnMaintenance(boolean reuseCapacityOnMaintenance)
Sets whether to callreuseCapacity()during pool maintenance (eviction). When enabled, the pool will attempt to reuse capacity at the end of each eviction run.- Parameters:
reuseCapacityOnMaintenance-trueto enable capacity reuse during maintenance,falseto disable- Since:
- 2.13.0
- See Also:
getReuseCapacityOnMaintenance()
-
setReuseCapacityOnReturn
public void setReuseCapacityOnReturn(boolean reuseCapacityOnReturn)
Sets whether to callreuseCapacity()when returning objects to the pool. When enabled, the pool will check if there are threads waiting to borrow objects and attempt to reuse capacity (across pools) on return.- Parameters:
reuseCapacityOnReturn-trueto enable capacity reuse on return,falseto disable- Since:
- 2.13.0
- See Also:
getReuseCapacityOnReturn()
-
toStringAppendFields
protected void toStringAppendFields(java.lang.StringBuilder builder)
Description copied from class:BaseObjectUsed by sub-classes to include the fields defined by the sub-class in theBaseObject.toString()output.- Overrides:
toStringAppendFieldsin classBaseGenericObjectPool<T>- Parameters:
builder- Field names and values are appended to this object
-
use
public void use(T pooledObject)
Description copied from interface:UsageTrackingCalled every time a pooled object is used to enable the pool to better track borrowed objects.- Specified by:
usein interfaceUsageTracking<K>- Parameters:
pooledObject- The object that is being used.- Since:
- 2.10.0
-
whenWaitersAddObject
private void whenWaitersAddObject(K key, LinkedBlockingDeque<PooledObject<T>> idleObjects)
When there is at least one thread waiting on the given deque, try to add an instance to pool under the given key. NOTE: there is no check that the key corresponds to the deque (it is assumed that the key was used to get the deque from the poolMap)- Parameters:
key- pool key.idleObjects- deque backing the pool under the given key
-
-