Constructor: |
public GenericKeyedObjectPool() {
this(null, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE,
DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
}
Create a new GenericKeyedObjectPool with no factory. |
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory) {
this(factory, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE,
DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy
objects if not null
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
Config config) {
this(factory, config.maxActive, config.whenExhaustedAction, config.maxWait, config.maxIdle, config.maxTotal,
config.minIdle, config.testOnBorrow, config.testOnReturn, config.timeBetweenEvictionRunsMillis,
config.numTestsPerEvictionRun, config.minEvictableIdleTimeMillis, config.testWhileIdle, config.lifo);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
config - a non-null GenericKeyedObjectPool.Config describing the configuration
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive) {
this(factory,maxActive, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE,
DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed from me at one time (see #setMaxActive )
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive,
byte whenExhaustedAction,
long maxWait) {
this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE, DEFAULT_TEST_ON_BORROW,
DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed from me at one time (see #setMaxActive )
whenExhaustedAction - the action to take when the pool is exhausted (see #setWhenExhaustedAction )
maxWait - the maximum amount of time to wait for an idle object when the pool is exhausted and
whenExhaustedAction is #WHEN_EXHAUSTED_BLOCK (otherwise ignored) (see #setMaxWait )
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive,
byte whenExhaustedAction,
long maxWait,
int maxIdle) {
this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN,
DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed from me at one time
(see #setMaxActive )
whenExhaustedAction - the action to take when the pool is exhausted (see #setWhenExhaustedAction )
maxWait - the maximum amount of time to wait for an idle object when the pool is exhausted and
whenExhaustedAction is #WHEN_EXHAUSTED_BLOCK (otherwise ignored) (see #setMaxWait )
maxIdle - the maximum number of idle objects in my pool (see #setMaxIdle )
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive,
byte whenExhaustedAction,
long maxWait,
boolean testOnBorrow,
boolean testOnReturn) {
this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE,testOnBorrow,testOnReturn,
DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed from me at one time (see #setMaxActive )
maxWait - the maximum amount of time to wait for an idle object when the pool is exhausted and
whenExhaustedAction is #WHEN_EXHAUSTED_BLOCK (otherwise ignored) (see #setMaxWait )
whenExhaustedAction - the action to take when the pool is exhausted (see #setWhenExhaustedAction )
testOnBorrow - whether or not to validate objects before they are returned by the #borrowObject
method (see #setTestOnBorrow )
testOnReturn - whether or not to validate objects after they are returned to the #returnObject
method (see #setTestOnReturn )
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive,
byte whenExhaustedAction,
long maxWait,
int maxIdle,
boolean testOnBorrow,
boolean testOnReturn) {
this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, testOnBorrow, testOnReturn,
DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed from me at one time
(see #setMaxActive )
whenExhaustedAction - the action to take when the pool is exhausted (see #setWhenExhaustedAction )
maxWait - the maximum amount of time to wait for an idle object when the pool is exhausted and
whenExhaustedAction is #WHEN_EXHAUSTED_BLOCK (otherwise ignored) (see #getMaxWait )
maxIdle - the maximum number of idle objects in my pool (see #setMaxIdle )
testOnBorrow - whether or not to validate objects before they are returned by the #borrowObject
method (see #setTestOnBorrow )
testOnReturn - whether or not to validate objects after they are returned to the #returnObject
method (see #setTestOnReturn )
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive,
byte whenExhaustedAction,
long maxWait,
int maxIdle,
boolean testOnBorrow,
boolean testOnReturn,
long timeBetweenEvictionRunsMillis,
int numTestsPerEvictionRun,
long minEvictableIdleTimeMillis,
boolean testWhileIdle) {
this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, GenericKeyedObjectPool.DEFAULT_MAX_TOTAL,
testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
minEvictableIdleTimeMillis, testWhileIdle);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed from me at one time
(see #setMaxActive )
whenExhaustedAction - the action to take when the pool is exhausted
(see #setWhenExhaustedAction )
maxWait - the maximum amount of time to wait for an idle object when the pool is exhausted and
whenExhaustedAction is #WHEN_EXHAUSTED_BLOCK (otherwise ignored) (see #setMaxWait )
maxIdle - the maximum number of idle objects in my pool (see #setMaxIdle )
testOnBorrow - whether or not to validate objects before they are returned by the #borrowObject
method (see #setTestOnBorrow )
testOnReturn - whether or not to validate objects after they are returned to the #returnObject
method (see #setTestOnReturn )
timeBetweenEvictionRunsMillis - the amount of time (in milliseconds) to sleep between examining idle
objects for eviction (see #setTimeBetweenEvictionRunsMillis )
numTestsPerEvictionRun - the number of idle objects to examine per run within the idle object eviction
thread (if any) (see #setNumTestsPerEvictionRun )
minEvictableIdleTimeMillis - the minimum number of milliseconds an object can sit idle in the pool before
it is eligible for eviction (see #setMinEvictableIdleTimeMillis )
testWhileIdle - whether or not to validate objects in the idle object eviction thread, if any
(see #setTestWhileIdle )
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive,
byte whenExhaustedAction,
long maxWait,
int maxIdle,
int maxTotal,
boolean testOnBorrow,
boolean testOnReturn,
long timeBetweenEvictionRunsMillis,
int numTestsPerEvictionRun,
long minEvictableIdleTimeMillis,
boolean testWhileIdle) {
this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, maxTotal,
GenericKeyedObjectPool.DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis,
numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed from me at one time
(see #setMaxActive )
whenExhaustedAction - the action to take when the pool is exhausted (see #setWhenExhaustedAction )
maxWait - the maximum amount of time to wait for an idle object when the pool is exhausted and
whenExhaustedAction is #WHEN_EXHAUSTED_BLOCK (otherwise ignored) (see #setMaxWait )
maxIdle - the maximum number of idle objects in my pool (see #setMaxIdle )
maxTotal - the maximum number of objects that can exists at one time (see #setMaxTotal )
testOnBorrow - whether or not to validate objects before they are returned by the #borrowObject
method (see #setTestOnBorrow )
testOnReturn - whether or not to validate objects after they are returned to the #returnObject
method (see #setTestOnReturn )
timeBetweenEvictionRunsMillis - the amount of time (in milliseconds) to sleep between examining idle
objects for eviction (see #setTimeBetweenEvictionRunsMillis )
numTestsPerEvictionRun - the number of idle objects to examine per run within the idle object eviction
thread (if any) (see #setNumTestsPerEvictionRun )
minEvictableIdleTimeMillis - the minimum number of milliseconds an object can sit idle in the pool
before it is eligible for eviction (see #setMinEvictableIdleTimeMillis )
testWhileIdle - whether or not to validate objects in the idle object eviction thread, if any
(see #setTestWhileIdle )
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive,
byte whenExhaustedAction,
long maxWait,
int maxIdle,
int maxTotal,
int minIdle,
boolean testOnBorrow,
boolean testOnReturn,
long timeBetweenEvictionRunsMillis,
int numTestsPerEvictionRun,
long minEvictableIdleTimeMillis,
boolean testWhileIdle) {
this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, maxTotal, minIdle, testOnBorrow, testOnReturn,
timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle,
DEFAULT_LIFO);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed at one time (see #setMaxActive )
whenExhaustedAction - the action to take when the pool is exhausted (see #setWhenExhaustedAction )
maxWait - the maximum amount of time to wait for an idle object when the pool is exhausted and
whenExhaustedAction is #WHEN_EXHAUSTED_BLOCK (otherwise ignored) (see #setMaxWait )
maxIdle - the maximum number of idle objects in my pool (see #setMaxIdle )
maxTotal - the maximum number of objects that can exists at one time (see #setMaxTotal )
minIdle - the minimum number of idle objects to have in the pool at any one time (see #setMinIdle )
testOnBorrow - whether or not to validate objects before they are returned by the #borrowObject
method (see #setTestOnBorrow )
testOnReturn - whether or not to validate objects after they are returned to the #returnObject
method (see #setTestOnReturn )
timeBetweenEvictionRunsMillis - the amount of time (in milliseconds) to sleep between examining idle
objects
for eviction (see #setTimeBetweenEvictionRunsMillis )
numTestsPerEvictionRun - the number of idle objects to examine per run within the idle object eviction
thread (if any) (see #setNumTestsPerEvictionRun )
minEvictableIdleTimeMillis - the minimum number of milliseconds an object can sit idle in the pool before
it is eligible for eviction (see #setMinEvictableIdleTimeMillis )
testWhileIdle - whether or not to validate objects in the idle object eviction thread, if any
(see #setTestWhileIdle )
- since:
Pool - 1.3
|
public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory,
int maxActive,
byte whenExhaustedAction,
long maxWait,
int maxIdle,
int maxTotal,
int minIdle,
boolean testOnBorrow,
boolean testOnReturn,
long timeBetweenEvictionRunsMillis,
int numTestsPerEvictionRun,
long minEvictableIdleTimeMillis,
boolean testWhileIdle,
boolean lifo) {
_factory = factory;
_maxActive = maxActive;
_lifo = lifo;
switch (whenExhaustedAction) {
case WHEN_EXHAUSTED_BLOCK:
case WHEN_EXHAUSTED_FAIL:
case WHEN_EXHAUSTED_GROW:
_whenExhaustedAction = whenExhaustedAction;
break;
default:
throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
}
_maxWait = maxWait;
_maxIdle = maxIdle;
_maxTotal = maxTotal;
_minIdle = minIdle;
_testOnBorrow = testOnBorrow;
_testOnReturn = testOnReturn;
_timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
_numTestsPerEvictionRun = numTestsPerEvictionRun;
_minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
_testWhileIdle = testWhileIdle;
_poolMap = new HashMap();
_poolList = new CursorableLinkedList();
startEvictor(_timeBetweenEvictionRunsMillis);
}
Create a new GenericKeyedObjectPool using the specified values. Parameters:
factory - the KeyedPoolableObjectFactory to use to create, validate, and destroy objects
if not null
maxActive - the maximum number of objects that can be borrowed at one time
(see #setMaxActive )
whenExhaustedAction - the action to take when the pool is exhausted (see #setWhenExhaustedAction )
maxWait - the maximum amount of time to wait for an idle object when the pool is exhausted and
whenExhaustedAction is #WHEN_EXHAUSTED_BLOCK (otherwise ignored) (see #setMaxWait )
maxIdle - the maximum number of idle objects in my pool (see #setMaxIdle )
maxTotal - the maximum number of objects that can exists at one time (see #setMaxTotal )
minIdle - the minimum number of idle objects to have in the pool at any one time (see #setMinIdle )
testOnBorrow - whether or not to validate objects before they are returned by the #borrowObject
method (see #setTestOnBorrow )
testOnReturn - whether or not to validate objects after they are returned to the #returnObject
method (see #setTestOnReturn )
timeBetweenEvictionRunsMillis - the amount of time (in milliseconds) to sleep between examining idle
objects for eviction (see #setTimeBetweenEvictionRunsMillis )
numTestsPerEvictionRun - the number of idle objects to examine per run within the idle object eviction
thread (if any) (see #setNumTestsPerEvictionRun )
minEvictableIdleTimeMillis - the minimum number of milliseconds an object can sit idle in the pool before
it is eligible for eviction (see #setMinEvictableIdleTimeMillis )
testWhileIdle - whether or not to validate objects in the idle object eviction thread, if any
(see #setTestWhileIdle )
lifo - whether or not the pools behave as LIFO (last in first out) queues (see #setLifo )
- since:
Pool - 1.4
|
Method from org.apache.commons.pool.impl.GenericKeyedObjectPool Detail: |
public void addObject(Object key) throws Exception {
assertOpen();
if (_factory == null) {
throw new IllegalStateException("Cannot add objects without a factory.");
}
Object obj = _factory.makeObject(key);
try {
assertOpen();
addObjectToPool(key, obj, false);
} catch (IllegalStateException ex) { // Pool closed
try {
_factory.destroyObject(key, obj);
} catch (Exception ex2) {
// swallow
}
throw ex;
}
}
Create an object using the factory ,
passivate it, and then place it in the idle object pool.
addObject is useful for "pre-loading" a pool with idle objects. |
public Object borrowObject(Object key) throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch(key);
byte whenExhaustedAction;
long maxWait;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
whenExhaustedAction = _whenExhaustedAction;
maxWait = _maxWait;
// Add this request to the queue
_allocationQueue.add(latch);
// Work the allocation queue, allocating idle instances and
// instance creation permits in request arrival order
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated
if (null == latch.getPair()) {
// Check to see if we were allowed to create one
if (latch.mayCreate()) {
// allow new object to be created
} else {
// the pool is exhausted
switch(whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
synchronized (this) {
// Make sure another thread didn't allocate us an object
// or permit a new object to be created
if (latch.getPair() == null && !latch.mayCreate()) {
_allocationQueue.remove(latch);
latch.getPool().incrementInternalProcessingCount();
}
}
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
// Make sure allocate hasn't already assigned an object
// in a different thread or permitted a new object to be created
if (latch.getPair() != null || latch.mayCreate()) {
break;
}
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
// Before we wait, make sure another thread didn't allocate us an object
// or permit a new object to be created
if (latch.getPair() == null && !latch.mayCreate()) {
if (maxWait < = 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
} else {
break;
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if (maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
synchronized (this) {
// Make sure allocate hasn't already assigned an object
// in a different thread or permitted a new object to be created
if (latch.getPair() == null && !latch.mayCreate()) {
_allocationQueue.remove(latch);
} else {
break;
}
}
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction +
" not recognized.");
}
}
}
boolean newlyCreated = false;
if (null == latch.getPair()) {
try {
Object obj = _factory.makeObject(key);
latch.setPair(new ObjectTimestampPair(obj));
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
latch.getPool().decrementInternalProcessingCount();
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(key, latch.getPair().value);
if (_testOnBorrow && !_factory.validateObject(key, latch.getPair().value)) {
throw new Exception("ValidateObject failed");
}
synchronized (this) {
latch.getPool().decrementInternalProcessingCount();
latch.getPool().incrementActiveCount();
}
return latch.getPair().value;
} catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(key, latch.getPair().value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
latch.getPool().decrementInternalProcessingCount();
if (!newlyCreated) {
latch.reset();
_allocationQueue.add(0, latch);
}
allocate();
}
if (newlyCreated) {
throw new NoSuchElementException(
"Could not create a validated object, cause: " +
e.getMessage());
}
else {
continue; // keep looping
}
}
}
}
Borrows an object from the keyed pool associated with the given key.
If there is an idle instance available in the pool associated with the given key, then
either the most-recently returned (if lifo == true) or "oldest" (lifo == false)
instance sitting idle in the pool will be 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 associated with the given key, behavior
depends on the maxActive , maxTotal , and (if applicable)
whenExhaustedAction and maxWait properties. If the
number of instances checked out from the pool under the given key is less than maxActive and
the total number of instances in circulation (under all keys) is less than maxTotal , a new instance
is created, activated and (if applicable) validated and returned to the caller.
If the associated keyed pool is exhausted (no available idle instances and no capacity to create new ones),
this method will either block (#WHEN_EXHAUSTED_BLOCK ), throw a NoSuchElementException
(#WHEN_EXHAUSTED_FAIL ), or grow (#WHEN_EXHAUSTED_GROW - ignoring maxActive, maxTotal properties).
The length of time that this method will block when whenExhaustedAction == WHEN_EXHAUSTED_BLOCK
is determined by the maxWait property.
When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances
to become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads receive
available instances in request arrival order.
|
public void clear() {
Map toDestroy = new HashMap();
synchronized (this) {
for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) {
Object key = it.next();
ObjectQueue pool = (ObjectQueue)_poolMap.get(key);
// Copy objects to new list so pool.queue can be cleared inside
// the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
it.remove();
_poolList.remove(key);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
}
destroy(toDestroy);
}
Clears any objects sitting idle in the pool by removing them from the
idle instance pool and then invoking the configured
KeyedPoolableObjectFactory#destroyObject(Object, Object) 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. It locks
the pool only during instance removal. Additional instances may be returned
while removed items are being destroyed.
|
public void clear(Object key) {
Map toDestroy = new HashMap();
final ObjectQueue pool;
synchronized (this) {
pool = (ObjectQueue)(_poolMap.remove(key));
if (pool == null) {
return;
} else {
_poolList.remove(key);
}
// Copy objects to new list so pool.queue can be cleared inside
// the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
destroy(toDestroy);
}
Clears the specified pool, removing all pooled instances corresponding to the given key . |
public void clearOldest() {
// Map of objects to destroy my key
final Map toDestroy = new HashMap();
// build sorted map of idle objects
final Map map = new TreeMap();
synchronized (this) {
for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) {
final Object key = keyiter.next();
final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue;
for (Iterator it = list.iterator(); it.hasNext();) {
// each item into the map uses the objectimestamppair object
// as the key. It then gets sorted based on the timstamp field
// each value in the map is the parent list it belongs in.
map.put(it.next(), key);
}
}
// Now iterate created map and kill the first 15% plus one to account for zero
Set setPairKeys = map.entrySet();
int itemsToRemove = ((int) (map.size() * 0.15)) + 1;
Iterator iter = setPairKeys.iterator();
while (iter.hasNext() && itemsToRemove > 0) {
Map.Entry entry = (Map.Entry) iter.next();
// kind of backwards on naming. In the map, each key is the objecttimestamppair
// because it has the ordering with the timestamp value. Each value that the
// key references is the key of the list it belongs to.
Object key = entry.getValue();
ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey();
final CursorableLinkedList list =
((ObjectQueue)(_poolMap.get(key))).queue;
list.remove(pairTimeStamp);
if (toDestroy.containsKey(key)) {
((List)toDestroy.get(key)).add(pairTimeStamp);
} else {
List listForKey = new ArrayList();
listForKey.add(pairTimeStamp);
toDestroy.put(key, listForKey);
}
// if that was the last object for that key, drop that pool
if (list.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
_totalIdle--;
_totalInternalProcessing++;
itemsToRemove--;
}
}
destroy(toDestroy);
}
Clears oldest 15% of objects in pool. The method sorts the
objects into a TreeMap and then iterates the first 15% for removal. |
public void close() throws Exception {
super.close();
synchronized (this) {
clear();
if (null != _evictionCursor) {
_evictionCursor.close();
_evictionCursor = null;
}
if (null != _evictionKeyCursor) {
_evictionKeyCursor.close();
_evictionKeyCursor = null;
}
startEvictor(-1L);
}
}
|
synchronized String debugInfo() {
StringBuffer buf = new StringBuffer();
buf.append("Active: ").append(getNumActive()).append("\n");
buf.append("Idle: ").append(getNumIdle()).append("\n");
Iterator it = _poolMap.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
buf.append("\t").append(key).append(" ").append(_poolMap.get(key)).append("\n");
}
return buf.toString();
}
|
public void evict() throws Exception {
Object key = null;
boolean testWhileIdle;
long minEvictableIdleTimeMillis;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
testWhileIdle = _testWhileIdle;
minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis;
// Initialize key to last key value
if (_evictionKeyCursor != null &&
_evictionKeyCursor._lastReturned != null) {
key = _evictionKeyCursor._lastReturned.value();
}
}
for (int i=0, m=getNumTests(); i< m; i++) {
final ObjectTimestampPair pair;
synchronized (this) {
// make sure pool map is not empty; otherwise do nothing
if (_poolMap == null || _poolMap.size() == 0) {
continue;
}
// if we don't have a key cursor, then create one
if (null == _evictionKeyCursor) {
resetEvictionKeyCursor();
key = null;
}
// if we don't have an object cursor, create one
if (null == _evictionCursor) {
// if the _evictionKeyCursor has a next value, use this key
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else {
// Reset the key cursor and try again
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
if (_evictionCursor == null) {
continue; // should never happen; do nothing
}
// If eviction cursor is exhausted, try to move
// to the next key and reset
if ((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else { // Need to reset Key cursor
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
}
if ((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
continue; // reset failed, do nothing
}
// if LIFO and the _evictionCursor has a previous object,
// or FIFO and _evictionCursor has a next object, test it
pair = _lifo ?
(ObjectTimestampPair) _evictionCursor.previous() :
(ObjectTimestampPair) _evictionCursor.next();
_evictionCursor.remove();
_totalIdle--;
_totalInternalProcessing++;
}
boolean removeObject=false;
if ((minEvictableIdleTimeMillis > 0) &&
(System.currentTimeMillis() - pair.tstamp >
minEvictableIdleTimeMillis)) {
removeObject=true;
}
if (testWhileIdle && removeObject == false) {
boolean active = false;
try {
_factory.activateObject(key,pair.value);
active = true;
} catch(Exception e) {
removeObject=true;
}
if (active) {
if (!_factory.validateObject(key,pair.value)) {
removeObject=true;
} else {
try {
_factory.passivateObject(key,pair.value);
} catch(Exception e) {
removeObject=true;
}
}
}
}
if (removeObject) {
try {
_factory.destroyObject(key, pair.value);
} catch(Exception e) {
// ignored
} finally {
// Do not remove the key from the _poolList or _poolmap,
// even if the list stored in the _poolMap for this key is
// empty when minIdle > 0.
//
// Otherwise if it was the last object for that key,
// drop that pool
if (_minIdle == 0) {
synchronized (this) {
ObjectQueue objectQueue =
(ObjectQueue)_poolMap.get(key);
if (objectQueue != null &&
objectQueue.queue.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
}
}
}
}
synchronized (this) {
if (!removeObject) {
_evictionCursor.add(pair);
_totalIdle++;
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_totalInternalProcessing--;
}
}
}
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 keyed pools
in sequence, cycling through the keys and examining objects in
oldest-to-youngest order within the keyed pools.
|
public synchronized boolean getLifo() {
return _lifo;
}
Whether or not the idle object pools act as LIFO queues. True means
that borrowObject returns the most recently used ("last in") idle object
in a pool (if there are idle instances available). False means that
the pools behave as FIFO queues - objects are taken from idle object
pools in the order that they are returned. |
public synchronized int getMaxActive() {
return _maxActive;
}
Returns the cap on the number of object instances allocated by the pool
(checked out or idle), per key.
A negative value indicates no limit. |
public synchronized int getMaxIdle() {
return _maxIdle;
}
Returns the cap on the number of "idle" instances per key. |
public synchronized int getMaxTotal() {
return _maxTotal;
}
Returns the overall maximum number of objects (across pools) that can
exist at one time. A negative value indicates no limit. |
public synchronized long getMaxWait() {
return _maxWait;
}
|
public synchronized long getMinEvictableIdleTimeMillis() {
return _minEvictableIdleTimeMillis;
}
Returns the minimum amount of time an object may sit idle in the pool
before it is eligible for eviction by the idle object evictor
(if any). |
public synchronized int getMinIdle() {
return _minIdle;
}
Returns the minimum number of idle objects to maintain in each of the keyed
pools. This setting has no effect unless
timeBetweenEvictionRunsMillis > 0 and attempts to ensure
that each pool has the required minimum number of instances are only
made during idle object eviction runs. |
public synchronized int getNumActive() {
return _totalActive;
}
Returns the total number of instances current borrowed from this pool but not yet returned. |
public synchronized int getNumActive(Object key) {
final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key));
return pool != null ? pool.activeCount : 0;
}
Returns the number of instances currently borrowed from but not yet returned
to the pool corresponding to the given key . |
public synchronized int getNumIdle() {
return _totalIdle;
}
Returns the total number of instances currently idle in this pool. |
public synchronized int getNumIdle(Object key) {
final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key));
return pool != null ? pool.queue.size() : 0;
}
Returns the number of instances corresponding to the given key currently idle in this pool. |
public synchronized int getNumTestsPerEvictionRun() {
return _numTestsPerEvictionRun;
}
Returns the max number of objects to examine during each run of the
idle object evictor thread (if any). |
public boolean getTestOnBorrow() {
return _testOnBorrow;
}
When true , objects will be
validated
before being returned by the #borrowObject
method. If the object fails to validate,
it will be dropped from the pool, and we will attempt
to borrow another. |
public boolean getTestOnReturn() {
return _testOnReturn;
}
|
public synchronized boolean getTestWhileIdle() {
return _testWhileIdle;
}
When true , objects will be
validated
by the idle object evictor (if any). If an object
fails to validate, it will be dropped from the pool. |
public synchronized long getTimeBetweenEvictionRunsMillis() {
return _timeBetweenEvictionRunsMillis;
}
Returns the number of milliseconds to sleep between runs of the
idle object evictor thread.
When non-positive, no idle object evictor thread will be
run. |
public synchronized byte getWhenExhaustedAction() {
return _whenExhaustedAction;
}
Returns the action to take when the #borrowObject method
is invoked when the pool is exhausted (the maximum number
of "active" objects has been reached). |
public void invalidateObject(Object key,
Object obj) throws Exception {
try {
_factory.destroyObject(key, obj);
} finally {
synchronized (this) {
ObjectQueue pool = (ObjectQueue) (_poolMap.get(key));
if (null == pool) {
pool = new ObjectQueue();
_poolMap.put(key, pool);
_poolList.add(key);
}
pool.decrementActiveCount();
allocate(); // _totalActive has changed
}
}
}
Invalidates the object instance associated with the given key. Decrements the active count
associated with the given keyed pool and destroys the instance.
|
public synchronized void preparePool(Object key,
boolean populateImmediately) {
ObjectQueue pool = (ObjectQueue)(_poolMap.get(key));
if (null == pool) {
pool = new ObjectQueue();
_poolMap.put(key,pool);
_poolList.add(key);
}
if (populateImmediately) {
try {
// Create the pooled objects
ensureMinIdle(key);
}
catch (Exception e) {
//Do nothing
}
}
}
Registers a key for pool control.
If populateImmediately is true and
minIdle > 0, the pool under the given key will be
populated immediately with minIdle idle instances. |
public void returnObject(Object key,
Object obj) throws Exception {
try {
addObjectToPool(key, obj, true);
} catch (Exception e) {
if (_factory != null) {
try {
_factory.destroyObject(key, obj);
} catch (Exception e2) {
// swallowed
}
// TODO: Correctness here depends on control in addObjectToPool.
// These two methods should be refactored, removing the
// "behavior flag", decrementNumActive, from addObjectToPool.
ObjectQueue pool = (ObjectQueue) (_poolMap.get(key));
if (pool != null) {
synchronized(this) {
pool.decrementActiveCount();
allocate();
}
}
}
}
}
Returns an object to a keyed pool.
For the pool to function correctly, the object instance must have been borrowed
from the pool (under the same key) and not yet returned. Repeated returnObject calls on
the same object/key pair (with no borrowObject calls in between) will result in multiple
references to the object in the idle instance pool.
If maxIdle is 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 pool under the given key. In this case, if validation fails, the instance is destroyed.
|
public synchronized void setConfig(Config conf) {
setMaxIdle(conf.maxIdle);
setMaxActive(conf.maxActive);
setMaxTotal(conf.maxTotal);
setMinIdle(conf.minIdle);
setMaxWait(conf.maxWait);
setWhenExhaustedAction(conf.whenExhaustedAction);
setTestOnBorrow(conf.testOnBorrow);
setTestOnReturn(conf.testOnReturn);
setTestWhileIdle(conf.testWhileIdle);
setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun);
setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
}
|
public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException {
Map toDestroy = new HashMap();
synchronized (this) {
assertOpen();
if (0 < getNumActive()) {
throw new IllegalStateException("Objects are already active");
} else {
for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) {
Object key = it.next();
ObjectQueue pool = (ObjectQueue)_poolMap.get(key);
if (pool != null) {
// Copy objects to new list so pool.queue can be cleared
// inside the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
it.remove();
_poolList.remove(key);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
}
_factory = factory;
}
}
destroy(toDestroy);
}
Sets the keyed poolable object factory associated with this pool.
If this method is called when objects are checked out of any of the keyed pools,
an IllegalStateException is thrown. Calling this method also has the side effect of
destroying any idle instances in existing keyed pools.
|
public synchronized void setLifo(boolean lifo) {
this._lifo = lifo;
}
Sets the LIFO property of the pools. True means that borrowObject returns
the most recently used ("last in") idle object in a pool (if there are
idle instances available). False means that the pools behave as FIFO
queues - objects are taken from idle object pools in the order that
they are returned. |
public synchronized void setMaxActive(int maxActive) {
_maxActive = maxActive;
allocate();
}
Sets the cap on the number of object instances managed by the pool per key. |
public synchronized void setMaxIdle(int maxIdle) {
_maxIdle = maxIdle;
allocate();
}
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 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. |
public synchronized void setMaxTotal(int maxTotal) {
_maxTotal = maxTotal;
allocate();
}
Sets the cap on the total number of instances from all pools combined.
When maxTotal is set to a
positive value and borrowObject is invoked
when at the limit with no idle instances available, an attempt is made to
create room by clearing the oldest 15% of the elements from the keyed
pools. |
public synchronized void setMaxWait(long maxWait) {
_maxWait = maxWait;
}
|
public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
_minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
Sets the minimum amount of time an object may sit idle in the pool
before it is eligible for eviction by the idle object evictor
(if any).
When non-positive, no objects will be evicted from the pool
due to idle time alone. |
public synchronized void setMinIdle(int poolSize) {
_minIdle = poolSize;
}
Sets the minimum number of idle objects to maintain in each of the keyed
pools. This setting has no effect unless
timeBetweenEvictionRunsMillis > 0 and attempts to ensure
that each pool has the required minimum number of instances are only
made during idle object eviction runs. |
public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
_numTestsPerEvictionRun = numTestsPerEvictionRun;
}
Sets the max number of objects to examine during each run of the
idle object evictor thread (if any).
When a negative value is supplied,
ceil(#getNumIdle() )/abs(#getNumTestsPerEvictionRun )
tests will be run. I.e., when the value is -n , roughly one n th of the
idle objects will be tested per run. When the value is positive, the number of tests
actually performed in each run will be the minimum of this value and the number of instances
idle in the pools. |
public void setTestOnBorrow(boolean testOnBorrow) {
_testOnBorrow = testOnBorrow;
}
When true , objects will be
validated
before being returned by the #borrowObject
method. If the object fails to validate,
it will be dropped from the pool, and we will attempt
to borrow another. |
public void setTestOnReturn(boolean testOnReturn) {
_testOnReturn = testOnReturn;
}
|
public synchronized void setTestWhileIdle(boolean testWhileIdle) {
_testWhileIdle = testWhileIdle;
}
When true , objects will be
validated
by the idle object evictor (if any). If an object
fails to validate, it will be dropped from the pool. |
public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
_timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
startEvictor(_timeBetweenEvictionRunsMillis);
}
Sets the number of milliseconds to sleep between runs of the
idle object evictor thread.
When non-positive, no idle object evictor thread will be
run. |
public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) {
switch(whenExhaustedAction) {
case WHEN_EXHAUSTED_BLOCK:
case WHEN_EXHAUSTED_FAIL:
case WHEN_EXHAUSTED_GROW:
_whenExhaustedAction = whenExhaustedAction;
allocate();
break;
default:
throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
}
}
Sets the action to take when the #borrowObject method
is invoked when the pool is exhausted (the maximum number
of "active" objects has been reached). |
protected synchronized void startEvictor(long delay) {
if (null != _evictor) {
EvictionTimer.cancel(_evictor);
_evictor = null;
}
if (delay > 0) {
_evictor = new Evictor();
EvictionTimer.schedule(_evictor, delay, delay);
}
}
Start the eviction thread or service, or when
delay is non-positive, stop it
if it is already running. |