Top Description Inners Fields Constructors Methods
org.apache.commons.pool2.impl

public Class GenericKeyedObjectPool<K, T>

extends BaseGenericObjectPool<T>
implements KeyedObjectPool<K, T>, GenericKeyedObjectPoolMXBean<K>, UsageTracking<T>
Class Inheritance
All Implemented Interfaces
org.apache.commons.pool2.UsageTracking, org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean, org.apache.commons.pool2.KeyedObjectPool, java.io.Closeable, java.lang.AutoCloseable
Type Parameters
<K>
The type of keys maintained by this pool.
<T>
Type of element pooled in this pool.
Imports
java.time.Duration, .Instant, java.util.ArrayList, .Deque, .HashMap, .Iterator, .List, .Map, .Map.Entry, .NoSuchElementException, .Objects, .TreeMap, java.util.concurrent.BlockingDeque, .ConcurrentHashMap, java.util.concurrent.atomic.AtomicBoolean, .AtomicInteger, .AtomicLong, java.util.concurrent.locks.Lock, .ReadWriteLock, .ReentrantReadWriteLock, java.util.stream.Collectors, org.apache.commons.pool2.DestroyMode, .KeyedObjectPool, .KeyedPooledObjectFactory, .PoolUtils, .PooledObject, .PooledObjectState, .SwallowedExceptionListener, .UsageTracking

A configurable KeyedObjectPool implementation.

When coupled with the appropriate KeyedPooledObjectFactory, GenericKeyedObjectPool provides robust pooling functionality for keyed objects. A GenericKeyedObjectPool can be viewed as a map of sub-pools, keyed on the (unique) key values provided to the preparePool, addObject or borrowObject methods. 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 containing GenericKeyedObjectPool.

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 and Inner Type Summary

Modifier and TypeClass and Description
private static class
GenericKeyedObjectPool.ObjectDeque<
type of objects in the pool
S
>

Maintains information on the per key queue for a given key.

Field Summary

Modifier and TypeField and Description
private K
private Iterator<K>
private final KeyedPooledObjectFactory<K, T>
private final boolean
private final ReadWriteLock
private volatile int
private volatile int
private volatile int
private final AtomicInteger
private static final String
private final ArrayList<K>
private final ConcurrentHashMap<K, GenericKeyedObjectPool.ObjectDeque<T>>
private volatile boolean
private volatile boolean
private static final Integer
Inherited from org.apache.commons.pool2.impl.BaseGenericObjectPool:
abandonedConfigclosedcloseLockcreatedCountdestroyedByBorrowValidationCountdestroyedByEvictorCountdestroyedCountevictionIteratorevictionLockMEAN_TIMING_STATS_CACHE_SIZE

Constructor Summary

AccessConstructor and Description
public
GenericKeyedObjectPool(final KeyedPooledObjectFactory<K, T>
the factory to be used to create entries
factory
)

Constructs a new GenericKeyedObjectPool using defaults from GenericKeyedObjectPoolConfig.

public
GenericKeyedObjectPool(final KeyedPooledObjectFactory<K, T>
the factory to be used to create entries
factory
,
final GenericKeyedObjectPoolConfig<T>
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.
config
)

Constructs a new GenericKeyedObjectPool using a specific configuration.

public
GenericKeyedObjectPool(final KeyedPooledObjectFactory<K, T>
The object factory to be used to create object instances used by this pool
factory
,
final GenericKeyedObjectPoolConfig<T>
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.
config
,
final AbandonedConfig
Configuration for abandoned object identification and removal. The configuration is used by value.
abandonedConfig
)

Creates a new GenericKeyedObjectPool that tracks and destroys objects that are checked out, but never returned to the pool.

Method Summary

Modifier and TypeMethod and Description
private void
addIdleObject(final K
The key to associate with the idle object
key
,
final PooledObject<T>
The wrapped object to add.
p
)

Add an object to the set of idle objects for a given key.

public void
addObject(final K
the key a new instance should be added to
key
)

Implements org.apache.commons.pool2.KeyedObjectPool.addObject.

Create an object using the factory, passivate it, and then place it in the idle object pool.

public T
public T

Returns:

object instance from the keyed pool
borrowObject
(final K
pool key
key
,
final Duration
The time to wait for an object to become available
maxWaitDuration
)

Borrows an object from the sub-pool associated with the given key using the specified waiting time which only applies if getBlockWhenExhausted() is true.

public T

Returns:

object instance from the keyed pool
borrowObject
(final K
pool key
key
,
final long
The time to wait in milliseconds for an object to become available
maxWaitMillis
)

Borrows an object from the sub-pool associated with the given key using the specified waiting time which only applies if getBlockWhenExhausted() is true.

private int

Returns:

The number of new objects to create
calculateDeficit
(final GenericKeyedObjectPool.ObjectDeque<T>
The set of objects to check
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.

public void
clear()

Implements org.apache.commons.pool2.KeyedObjectPool.clear.

Clears any objects sitting idle in the pool by removing them from the idle instance sub-pools and then invoking the configured PoolableObjectFactory's KeyedPooledObjectFactory#destroyObject(Object, PooledObject) method on each idle instance.

public void
clear(final K
the key to clear
key
)

Implements org.apache.commons.pool2.KeyedObjectPool.clear.

Clears the specified sub-pool, removing all pooled instances corresponding to the given key.

public void
clear(final K
the key to clear
key
,
final boolean
whether or not to reuse freed capacity
reuseCapacity
)

Clears the specified sub-pool, removing all pooled instances corresponding to the given key.

public void
clearOldest()

Clears oldest 15% of objects in pool.

public void
private PooledObject<T>

Returns:

The new, wrapped pooled object. May return null.
create
(final K
Key associated with new pooled object.
key
,
final Duration
The time to wait in this method. If negative or ZERO, this method may wait indefinitely.
maxWaitDuration
)

Creates a new pooled object or null.

private void
deregister(final K
The key to de-register
k
)

De-register the use of a key by an object.

private boolean

Returns:

true if the object was destroyed, otherwise false
destroy
(final K
The key associated with the object to destroy
key
,
final PooledObject<T>
The wrapped object to be destroyed
toDestroy
,
final boolean
Should the object be destroyed even if it is not currently in the set of idle objects for the given key
always
,
final DestroyMode
DestroyMode context provided to the factory
destroyMode
)

Destroy the wrapped, pooled object.

pack-priv void
ensureMinIdle()

Implements abstract org.apache.commons.pool2.impl.BaseGenericObjectPool.ensureMinIdle.

Tries to ensure that the configured minimum number of idle instances are available in the pool.

private void
ensureMinIdle(final K
The key to check for idle objects
key
)

Try to ensure that the configured number of minimum idle objects is available in the pool for the given key.

public void
evict()

Implements abstract org.apache.commons.pool2.impl.BaseGenericObjectPool.evict.

Perform numTests idle object eviction tests, evicting examined objects that meet the criteria for eviction.

public KeyedPooledObjectFactory<K, T>

Returns:

the factory
getFactory
()

Gets a reference to the factory used to create, destroy and validate the objects used by this pool.

public List<K>

Returns:

a copy of the pool key list.
getKeys
()

Overrides default org.apache.commons.pool2.KeyedObjectPool.getKeys.

Gets a copy of the pool key list.

public int

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
getMaxIdlePerKey
()

Implements org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean.getMaxIdlePerKey.

Gets the cap on the number of "idle" instances per key in the pool.

public int

Returns:

the limit on the number of active instances per key
getMaxTotalPerKey
()

Implements org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean.getMaxTotalPerKey.

Gets the limit on the number of object instances allocated by the pool (checked out or idle), per key.

public int

Returns:

minimum size of the each keyed pool
getMinIdlePerKey
()

Implements org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean.getMinIdlePerKey.

Gets the target for the minimum number of idle objects to maintain in each of the keyed sub-pools.

public int
getNumActive()

Implements org.apache.commons.pool2.KeyedObjectPool.getNumActive, org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean.getNumActive.

Gets the total number of instances currently borrowed from this pool but not yet returned.

public int
getNumActive(final K key)

Implements org.apache.commons.pool2.KeyedObjectPool.getNumActive.

Gets the number of instances currently borrowed from but not yet returned to the pool corresponding to the given key.

public Map<String, Integer>
public int
public int
getNumIdle(final K key)

Implements org.apache.commons.pool2.KeyedObjectPool.getNumIdle.

Gets the number of instances corresponding to the given key currently idle in this pool.

private int

Returns:

The number of objects to test for validity
getNumTests
()

Gets the number of objects to test in a run of the idle object evictor.

public int

Returns:

The estimate of the number of threads currently blocked waiting for an object from the pool
getNumWaiters
()

Implements org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean.getNumWaiters.

Gets an estimate of the number of threads currently blocked waiting for an object from the pool.

public Map<String, Integer>

Returns:

The estimate of the number of threads currently blocked waiting for an object from the pool for each key
getNumWaitersByKey
()

Implements org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean.getNumWaitersByKey.

Gets an estimate of the number of threads currently blocked waiting for an object from the pool for each key.

public boolean

Returns:

true if capacity reuse is enabled during maintenance, false otherwise
getReuseCapacityOnMaintenance
()

Gets whether to call reuseCapacity() during pool maintenance (eviction).

public boolean

Returns:

true if capacity reuse is enabled on return, false otherwise
getReuseCapacityOnReturn
()

Gets whether to call reuseCapacity() when returning objects to the pool.

pack-priv String
private boolean

Returns:

true if there is at least one thread waiting otherwise false
hasBorrowWaiters
()

Tests to see if there are any threads currently waiting to borrow objects but are blocked waiting for more objects to become available.

public void
invalidateObject(final K
pool key
key
,
final T
instance to invalidate
obj
)

Implements org.apache.commons.pool2.KeyedObjectPool.invalidateObject.

Invalidates an object from the pool.

public void
invalidateObject(final K
pool key
key
,
final T
instance to invalidate
obj
,
final DestroyMode
DestroyMode context provided to factory
destroyMode
)

Overrides default org.apache.commons.pool2.KeyedObjectPool.invalidateObject.

Invalidates an object from the pool, using the provided DestroyMode.

public Map<String, List<DefaultPooledObjectInfo>>

Returns:

Information grouped by key on all the objects in the pool
listAllObjects
()

Implements org.apache.commons.pool2.impl.GenericKeyedObjectPoolMXBean.listAllObjects.

Provides information on all the objects in the pool, both idle (waiting to be borrowed) and active (currently borrowed).

public void
preparePool(final K
The key to register for pool control.
key
)

Registers a key for pool control and ensures that getMinIdlePerKey() idle instances are created.

private GenericKeyedObjectPool.ObjectDeque<T>

Returns:

The objects currently associated with the given key. If this method returns without throwing an exception then it will never return null.
register
(final K
The key to register
k
)

Register the use of a key by an object.

private void
removeAbandoned(final AbandonedConfig
The configuration to use to identify abandoned objects
abandonedConfig
)

Recovers abandoned objects which have been checked out but not used since longer than the removeAbandonedTimeout.

public void
returnObject(final K
pool key
key
,
final T
instance to return to the keyed pool
obj
)

Implements org.apache.commons.pool2.KeyedObjectPool.returnObject.

Returns an object to a keyed sub-pool.

private void
reuseCapacity()

Attempt to create one new instance to serve from the most heavily loaded pool that can add a new instance.

private void
reuseCapacity(final int
number of times to call reuseCapacity()
newCapacity
)

Call reuseCapacity() repeatedly.

public void
setConfig(final GenericKeyedObjectPoolConfig<T>
the new configuration to use. This is used by value.
conf
)

Sets the configuration.

public void
setMaxIdlePerKey(final int
the maximum number of "idle" instances that can be held in a given keyed sub-pool. Use a negative value for no limit
maxIdlePerKey
)

Sets the cap on the number of "idle" instances per key in the pool.

public void
setMaxTotalPerKey(final int
the limit on the number of active instances per key
maxTotalPerKey
)

Sets the limit on the number of object instances allocated by the pool (checked out or idle), per key.

public void
setMinIdlePerKey(final int
The minimum size of the each keyed pool
minIdlePerKey
)

Sets the target for the minimum number of idle objects to maintain in each of the keyed sub-pools.

public void
setReuseCapacityOnMaintenance(final boolean
true to enable capacity reuse during maintenance, false to disable
reuseCapacityOnMaintenance
)

Sets whether to call reuseCapacity() during pool maintenance (eviction).

public void
setReuseCapacityOnReturn(final boolean
true to enable capacity reuse on return, false to disable
reuseCapacityOnReturn
)

Sets whether to call reuseCapacity() when returning objects to the pool.

protected void
toStringAppendFields(final StringBuilder builder)

Overrides org.apache.commons.pool2.impl.BaseGenericObjectPool.toStringAppendFields.

Used by sub-classes to include the fields defined by the sub-class in the toString() output.

public void
use(final T pooledObject)

Implements org.apache.commons.pool2.UsageTracking.use.

Called every time a pooled object is used to enable the pool to better track borrowed objects.

private void
whenWaitersAddObject(final K
pool key.
key
,
final LinkedBlockingDeque<PooledObject<T>>
deque backing the pool under the given key
idleObjects
)

When there is at least one thread waiting on the given deque, try to add an instance to pool under the given key.

Inherited from org.apache.commons.pool2.impl.BaseGenericObjectPool:
appendStatsassertOpencreateRemoveListdurationSincegetBlockWhenExhaustedgetBorrowedCountgetCollectDetailedStatisticsgetCreatedCountgetCreationStackTracegetDestroyedByBorrowValidationCountgetDestroyedByEvictorCountgetDestroyedCountgetDurationBetweenEvictionRunsgetEvictionPolicygetEvictionPolicyClassNamegetEvictorShutdownTimeoutgetEvictorShutdownTimeoutDurationgetEvictorShutdownTimeoutMillisgetFairnessgetJmxNamegetLifogetLogAbandonedgetMaxBorrowWaitDurationgetMaxBorrowWaitTimeMillisgetMaxTotalgetMaxWaitDurationgetMaxWaitMillisgetMeanActiveDurationgetMeanActiveTimeMillisgetMeanBorrowWaitDurationgetMeanBorrowWaitTimeMillisgetMeanIdleDurationgetMeanIdleTimeMillisgetMessageStatisticsgetMinEvictableIdleDurationgetMinEvictableIdleTimegetMinEvictableIdleTimeMillisgetNumTestsPerEvictionRungetRemoveAbandonedOnBorrowgetRemoveAbandonedOnMaintenancegetRemoveAbandonedTimeoutgetRemoveAbandonedTimeoutDurationgetReturnedCountgetSoftMinEvictableIdleDurationgetSoftMinEvictableIdleTimegetSoftMinEvictableIdleTimeMillisgetSwallowedExceptionListenergetTestOnBorrowgetTestOnCreategetTestOnReturngetTestWhileIdlegetTimeBetweenEvictionRunsgetTimeBetweenEvictionRunsMillisisAbandonedConfigisClosedjmxUnregistermarkReturningStatesetAbandonedConfigsetBlockWhenExhaustedsetCollectDetailedStatisticssetConfigsetDurationBetweenEvictionRunssetEvictionPolicysetEvictionPolicyClassNamesetEvictionPolicyClassNamesetEvictorShutdownTimeoutsetEvictorShutdownTimeoutMillissetLifosetMaxTotalsetMaxWaitsetMaxWaitMillissetMessagesStatisticssetMinEvictableIdlesetMinEvictableIdleDurationsetMinEvictableIdleTimesetMinEvictableIdleTimeMillissetNumTestsPerEvictionRunsetSoftMinEvictableIdlesetSoftMinEvictableIdleDurationsetSoftMinEvictableIdleTimesetSoftMinEvictableIdleTimeMillissetSwallowedExceptionListenersetTestOnBorrowsetTestOnCreatesetTestOnReturnsetTestWhileIdlesetTimeBetweenEvictionRunssetTimeBetweenEvictionRunsMillisstartEvictorstopEvictorswallowExceptionupdateStatsBorrowupdateStatsReturnwait