001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 package org.apache.commons.pool.impl;
019
020 import java.util.ArrayList;
021 import java.util.Collection;
022 import java.util.HashMap;
023 import java.util.Iterator;
024 import java.util.LinkedList;
025 import java.util.List;
026 import java.util.Map;
027 import java.util.NoSuchElementException;
028 import java.util.Set;
029 import java.util.TreeMap;
030 import java.util.TimerTask;
031
032 import org.apache.commons.pool.BaseKeyedObjectPool;
033 import org.apache.commons.pool.KeyedObjectPool;
034 import org.apache.commons.pool.KeyedPoolableObjectFactory;
035
036 /**
037 * A configurable <code>KeyedObjectPool</code> implementation.
038 * <p>
039 * When coupled with the appropriate {@link KeyedPoolableObjectFactory},
040 * <code>GenericKeyedObjectPool</code> provides robust pooling functionality for
041 * keyed objects. A <code>GenericKeyedObjectPool</code> can be viewed as a map
042 * of pools, keyed on the (unique) key values provided to the
043 * {@link #preparePool preparePool}, {@link #addObject addObject} or
044 * {@link #borrowObject borrowObject} methods. Each time a new key value is
045 * provided to one of these methods, a new pool is created under the given key
046 * to be managed by the containing <code>GenericKeyedObjectPool.</code>
047 * </p>
048 * <p>A <code>GenericKeyedObjectPool</code> provides a number of configurable
049 * parameters:</p>
050 * <ul>
051 * <li>
052 * {@link #setMaxActive maxActive} controls the maximum number of objects
053 * (per key) that can allocated by the pool (checked out to client threads,
054 * or idle in the pool) at one time. When non-positive, there is no limit
055 * to the number of objects per key. When {@link #setMaxActive maxActive} is
056 * reached, the keyed pool is said to be exhausted. The default setting for
057 * this parameter is 8.
058 * </li>
059 * <li>
060 * {@link #setMaxTotal maxTotal} sets a global limit on the number of objects
061 * that can be in circulation (active or idle) within the combined set of
062 * pools. When non-positive, there is no limit to the total number of
063 * objects in circulation. When {@link #setMaxTotal maxTotal} is exceeded,
064 * all keyed pools are exhausted. When <code>maxTotal</code> is set to a
065 * positive value and {@link #borrowObject borrowObject} is invoked
066 * when at the limit with no idle instances available, an attempt is made to
067 * create room by clearing the oldest 15% of the elements from the keyed
068 * pools. The default setting for this parameter is -1 (no limit).
069 * </li>
070 * <li>
071 * {@link #setMaxIdle maxIdle} controls the maximum number of objects that can
072 * sit idle in the pool (per key) at any time. When negative, there
073 * is no limit to the number of objects that may be idle per key. The
074 * default setting for this parameter is 8.
075 * </li>
076 * <li>
077 * {@link #setWhenExhaustedAction whenExhaustedAction} specifies the
078 * behavior of the {@link #borrowObject borrowObject} method when a keyed
079 * pool is exhausted:
080 * <ul>
081 * <li>
082 * When {@link #setWhenExhaustedAction whenExhaustedAction} is
083 * {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject borrowObject} will throw
084 * a {@link NoSuchElementException}
085 * </li>
086 * <li>
087 * When {@link #setWhenExhaustedAction whenExhaustedAction} is
088 * {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject borrowObject} will create a new
089 * object and return it (essentially making {@link #setMaxActive maxActive}
090 * meaningless.)
091 * </li>
092 * <li>
093 * When {@link #setWhenExhaustedAction whenExhaustedAction}
094 * is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject borrowObject} will block
095 * (invoke {@link Object#wait() wait} until a new or idle object is available.
096 * If a positive {@link #setMaxWait maxWait}
097 * value is supplied, the {@link #borrowObject borrowObject} will block for at
098 * most that many milliseconds, after which a {@link NoSuchElementException}
099 * will be thrown. If {@link #setMaxWait maxWait} is non-positive,
100 * the {@link #borrowObject borrowObject} method will block indefinitely.
101 * </li>
102 * </ul>
103 * The default <code>whenExhaustedAction</code> setting is
104 * {@link #WHEN_EXHAUSTED_BLOCK}.
105 * </li>
106 * <li>
107 * When {@link #setTestOnBorrow testOnBorrow} is set, the pool will
108 * attempt to validate each object before it is returned from the
109 * {@link #borrowObject borrowObject} method. (Using the provided factory's
110 * {@link KeyedPoolableObjectFactory#validateObject validateObject} method.)
111 * Objects that fail to validate will be dropped from the pool, and a
112 * different object will be borrowed. The default setting for this parameter
113 * is <code>false.</code>
114 * </li>
115 * <li>
116 * When {@link #setTestOnReturn testOnReturn} is set, the pool will
117 * attempt to validate each object before it is returned to the pool in the
118 * {@link #returnObject returnObject} method. (Using the provided factory's
119 * {@link KeyedPoolableObjectFactory#validateObject validateObject}
120 * method.) Objects that fail to validate will be dropped from the pool.
121 * The default setting for this parameter is <code>false.</code>
122 * </li>
123 * </ul>
124 * <p>
125 * Optionally, one may configure the pool to examine and possibly evict objects
126 * as they sit idle in the pool and to ensure that a minimum number of idle
127 * objects is maintained for each key. This is performed by an
128 * "idle object eviction" thread, which runs asynchronously. Caution should be
129 * used when configuring this optional feature. Eviction runs require an
130 * exclusive synchronization lock on the pool, so if they run too frequently
131 * and / or incur excessive latency when creating, destroying or validating
132 * object instances, performance issues may result. The idle object eviction
133 * thread may be configured using the following attributes:
134 * <ul>
135 * <li>
136 * {@link #setTimeBetweenEvictionRunsMillis timeBetweenEvictionRunsMillis}
137 * indicates how long the eviction thread should sleep before "runs" of examining
138 * idle objects. When non-positive, no eviction thread will be launched. The
139 * default setting for this parameter is -1 (i.e., by default, idle object
140 * eviction is disabled).
141 * </li>
142 * <li>
143 * {@link #setMinEvictableIdleTimeMillis minEvictableIdleTimeMillis}
144 * specifies the minimum amount of time that an object may sit idle in the
145 * pool before it is eligible for eviction due to idle time. When
146 * non-positive, no object will be dropped from the pool due to idle time
147 * alone. This setting has no effect unless
148 * <code>timeBetweenEvictionRunsMillis > 0.</code> The default setting
149 * for this parameter is 30 minutes.
150 * </li>
151 * <li>
152 * {@link #setTestWhileIdle testWhileIdle} indicates whether or not idle
153 * objects should be validated using the factory's
154 * {@link KeyedPoolableObjectFactory#validateObject validateObject} method
155 * during idle object eviction runs. Objects that fail to validate will be
156 * dropped from the pool. This setting has no effect unless
157 * <code>timeBetweenEvictionRunsMillis > 0.</code> The default setting
158 * for this parameter is <code>false.</code>
159 * </li>
160 * <li>
161 * {@link #setMinIdle minIdle} sets a target value for the minimum number of
162 * idle objects (per key) that should always be available. If this parameter
163 * is set to a positive number and
164 * <code>timeBetweenEvictionRunsMillis > 0,</code> each time the idle object
165 * eviction thread runs, it will try to create enough idle instances so that
166 * there will be <code>minIdle</code> idle instances available under each
167 * key. This parameter is also used by {@link #preparePool preparePool}
168 * if <code>true</code> is provided as that method's
169 * <code>populateImmediately</code> parameter. The default setting for this
170 * parameter is 0.
171 * </li>
172 * </ul>
173 * <p>
174 * The pools can be configured to behave as LIFO queues with respect to idle
175 * objects - always returning the most recently used object from the pool,
176 * or as FIFO queues, where borrowObject always returns the oldest object
177 * in the idle object pool.
178 * <ul>
179 * <li>
180 * {@link #setLifo <i>Lifo</i>}
181 * determines whether or not the pools return idle objects in
182 * last-in-first-out order. The default setting for this parameter is
183 * <code>true.</code>
184 * </li>
185 * </ul>
186 * <p>
187 * GenericKeyedObjectPool is not usable without a {@link KeyedPoolableObjectFactory}. A
188 * non-<code>null</code> factory must be provided either as a constructor argument
189 * or via a call to {@link #setFactory setFactory} before the pool is used.
190 * </p>
191 * <p>
192 * Implementation note: To prevent possible deadlocks, care has been taken to
193 * ensure that no call to a factory method will occur within a synchronization
194 * block. See POOL-125 and DBCP-44 for more information.
195 * </p>
196 * @see GenericObjectPool
197 * @author Rodney Waldhoff
198 * @author Dirk Verbeeck
199 * @author Sandy McArthur
200 * @version $Revision: 791907 $ $Date: 2009-07-07 12:56:33 -0400 (Tue, 07 Jul 2009) $
201 * @since Pool 1.0
202 */
203 public class GenericKeyedObjectPool extends BaseKeyedObjectPool implements KeyedObjectPool {
204
205 //--- public constants -------------------------------------------
206
207 /**
208 * A "when exhausted action" type indicating that when the pool is
209 * exhausted (i.e., the maximum number of active objects has
210 * been reached), the {@link #borrowObject}
211 * method should fail, throwing a {@link NoSuchElementException}.
212 * @see #WHEN_EXHAUSTED_BLOCK
213 * @see #WHEN_EXHAUSTED_GROW
214 * @see #setWhenExhaustedAction
215 */
216 public static final byte WHEN_EXHAUSTED_FAIL = 0;
217
218 /**
219 * A "when exhausted action" type indicating that when the pool
220 * is exhausted (i.e., the maximum number
221 * of active objects has been reached), the {@link #borrowObject}
222 * method should block until a new object is available, or the
223 * {@link #getMaxWait maximum wait time} has been reached.
224 * @see #WHEN_EXHAUSTED_FAIL
225 * @see #WHEN_EXHAUSTED_GROW
226 * @see #setMaxWait
227 * @see #getMaxWait
228 * @see #setWhenExhaustedAction
229 */
230 public static final byte WHEN_EXHAUSTED_BLOCK = 1;
231
232 /**
233 * A "when exhausted action" type indicating that when the pool is
234 * exhausted (i.e., the maximum number
235 * of active objects has been reached), the {@link #borrowObject}
236 * method should simply create a new object anyway.
237 * @see #WHEN_EXHAUSTED_FAIL
238 * @see #WHEN_EXHAUSTED_GROW
239 * @see #setWhenExhaustedAction
240 */
241 public static final byte WHEN_EXHAUSTED_GROW = 2;
242
243 /**
244 * The default cap on the number of idle instances (per key) in the pool.
245 * @see #getMaxIdle
246 * @see #setMaxIdle
247 */
248 public static final int DEFAULT_MAX_IDLE = 8;
249
250 /**
251 * The default cap on the total number of active instances (per key)
252 * from the pool.
253 * @see #getMaxActive
254 * @see #setMaxActive
255 */
256 public static final int DEFAULT_MAX_ACTIVE = 8;
257
258 /**
259 * The default cap on the the overall maximum number of objects that can
260 * exist at one time.
261 * @see #getMaxTotal
262 * @see #setMaxTotal
263 */
264 public static final int DEFAULT_MAX_TOTAL = -1;
265
266 /**
267 * The default "when exhausted action" for the pool.
268 * @see #WHEN_EXHAUSTED_BLOCK
269 * @see #WHEN_EXHAUSTED_FAIL
270 * @see #WHEN_EXHAUSTED_GROW
271 * @see #setWhenExhaustedAction
272 */
273 public static final byte DEFAULT_WHEN_EXHAUSTED_ACTION = WHEN_EXHAUSTED_BLOCK;
274
275 /**
276 * The default maximum amount of time (in milliseconds) the
277 * {@link #borrowObject} method should block before throwing
278 * an exception when the pool is exhausted and the
279 * {@link #getWhenExhaustedAction "when exhausted" action} is
280 * {@link #WHEN_EXHAUSTED_BLOCK}.
281 * @see #getMaxWait
282 * @see #setMaxWait
283 */
284 public static final long DEFAULT_MAX_WAIT = -1L;
285
286 /**
287 * The default "test on borrow" value.
288 * @see #getTestOnBorrow
289 * @see #setTestOnBorrow
290 */
291 public static final boolean DEFAULT_TEST_ON_BORROW = false;
292
293 /**
294 * The default "test on return" value.
295 * @see #getTestOnReturn
296 * @see #setTestOnReturn
297 */
298 public static final boolean DEFAULT_TEST_ON_RETURN = false;
299
300 /**
301 * The default "test while idle" value.
302 * @see #getTestWhileIdle
303 * @see #setTestWhileIdle
304 * @see #getTimeBetweenEvictionRunsMillis
305 * @see #setTimeBetweenEvictionRunsMillis
306 */
307 public static final boolean DEFAULT_TEST_WHILE_IDLE = false;
308
309 /**
310 * The default "time between eviction runs" value.
311 * @see #getTimeBetweenEvictionRunsMillis
312 * @see #setTimeBetweenEvictionRunsMillis
313 */
314 public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L;
315
316 /**
317 * The default number of objects to examine per run in the
318 * idle object evictor.
319 * @see #getNumTestsPerEvictionRun
320 * @see #setNumTestsPerEvictionRun
321 * @see #getTimeBetweenEvictionRunsMillis
322 * @see #setTimeBetweenEvictionRunsMillis
323 */
324 public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3;
325
326 /**
327 * The default value for {@link #getMinEvictableIdleTimeMillis}.
328 * @see #getMinEvictableIdleTimeMillis
329 * @see #setMinEvictableIdleTimeMillis
330 */
331 public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L;
332
333 /**
334 * The default minimum level of idle objects in the pool.
335 * @since Pool 1.3
336 * @see #setMinIdle
337 * @see #getMinIdle
338 */
339 public static final int DEFAULT_MIN_IDLE = 0;
340
341 /**
342 * The default LIFO status. True means that borrowObject returns the
343 * most recently used ("last in") idle object in a pool (if there are
344 * idle instances available). False means that pools behave as FIFO
345 * queues - objects are taken from idle object pools in the order that
346 * they are returned.
347 * @see #setLifo
348 */
349 public static final boolean DEFAULT_LIFO = true;
350
351 //--- constructors -----------------------------------------------
352
353 /**
354 * Create a new <code>GenericKeyedObjectPool</code> with no factory.
355 *
356 * @see #GenericKeyedObjectPool(KeyedPoolableObjectFactory)
357 * @see #setFactory(KeyedPoolableObjectFactory)
358 */
359 public GenericKeyedObjectPool() {
360 this(null, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE,
361 DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
362 DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
363 }
364
365 /**
366 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
367 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy
368 * objects if not <code>null</code>
369 */
370 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory) {
371 this(factory, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE,
372 DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
373 DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
374 }
375
376 /**
377 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
378 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
379 * if not <code>null</code>
380 * @param config a non-<code>null</code> {@link GenericKeyedObjectPool.Config} describing the configuration
381 */
382 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, GenericKeyedObjectPool.Config config) {
383 this(factory, config.maxActive, config.whenExhaustedAction, config.maxWait, config.maxIdle, config.maxTotal,
384 config.minIdle, config.testOnBorrow, config.testOnReturn, config.timeBetweenEvictionRunsMillis,
385 config.numTestsPerEvictionRun, config.minEvictableIdleTimeMillis, config.testWhileIdle, config.lifo);
386 }
387
388 /**
389 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
390 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
391 * if not <code>null</code>
392 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
393 */
394 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive) {
395 this(factory,maxActive, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE,
396 DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
397 DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
398 }
399
400 /**
401 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
402 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
403 * if not <code>null</code>
404 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
405 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
406 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and
407 * <code>whenExhaustedAction</code> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
408 */
409 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction,
410 long maxWait) {
411 this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE, DEFAULT_TEST_ON_BORROW,
412 DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
413 DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
414 }
415
416 /**
417 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
418 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
419 * if not <code>null</code>
420 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
421 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and
422 * <code>whenExhaustedAction</code> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
423 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
424 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject}
425 * method (see {@link #setTestOnBorrow})
426 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject}
427 * method (see {@link #setTestOnReturn})
428 */
429 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction,
430 long maxWait, boolean testOnBorrow, boolean testOnReturn) {
431 this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE,testOnBorrow,testOnReturn,
432 DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
433 DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
434 }
435
436 /**
437 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
438 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
439 * if not <code>null</code>
440 * @param maxActive the maximum number of objects that can be borrowed from me at one time
441 * (see {@link #setMaxActive})
442 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
443 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and
444 * <code>whenExhaustedAction</code> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
445 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
446 */
447 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction,
448 long maxWait, int maxIdle) {
449 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN,
450 DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
451 DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
452 }
453
454 /**
455 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
456 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
457 * if not <code>null</code>
458 * @param maxActive the maximum number of objects that can be borrowed from me at one time
459 * (see {@link #setMaxActive})
460 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
461 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and
462 * <code>whenExhaustedAction</code> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
463 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
464 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject}
465 * method (see {@link #setTestOnBorrow})
466 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject}
467 * method (see {@link #setTestOnReturn})
468 */
469 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction,
470 long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn) {
471 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, testOnBorrow, testOnReturn,
472 DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
473 DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE);
474 }
475
476 /**
477 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
478 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
479 * if not <code>null</code>
480 * @param maxActive the maximum number of objects that can be borrowed from me at one time
481 * (see {@link #setMaxActive})
482 * @param whenExhaustedAction the action to take when the pool is exhausted
483 * (see {@link #setWhenExhaustedAction})
484 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and
485 * <code>whenExhaustedAction</code> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
486 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
487 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject}
488 * method (see {@link #setTestOnBorrow})
489 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject}
490 * method (see {@link #setTestOnReturn})
491 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle
492 * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
493 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction
494 * thread (if any) (see {@link #setNumTestsPerEvictionRun})
495 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before
496 * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis})
497 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any
498 * (see {@link #setTestWhileIdle})
499 */
500 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction,
501 long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis,
502 int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) {
503 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, GenericKeyedObjectPool.DEFAULT_MAX_TOTAL,
504 testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
505 minEvictableIdleTimeMillis, testWhileIdle);
506 }
507
508 /**
509 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
510 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
511 * if not <code>null</code>
512 * @param maxActive the maximum number of objects that can be borrowed from me at one time
513 * (see {@link #setMaxActive})
514 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
515 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and
516 * <code>whenExhaustedAction</code> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
517 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
518 * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal})
519 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject}
520 * method (see {@link #setTestOnBorrow})
521 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject}
522 * method (see {@link #setTestOnReturn})
523 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle
524 * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
525 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction
526 * thread (if any) (see {@link #setNumTestsPerEvictionRun})
527 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool
528 * before it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis})
529 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any
530 * (see {@link #setTestWhileIdle})
531 */
532 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction,
533 long maxWait, int maxIdle, int maxTotal, boolean testOnBorrow, boolean testOnReturn,
534 long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis,
535 boolean testWhileIdle) {
536 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, maxTotal,
537 GenericKeyedObjectPool.DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis,
538 numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle);
539 }
540
541 /**
542 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
543 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
544 * if not <code>null</code>
545 * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive})
546 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
547 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and
548 * <code>whenExhaustedAction</code> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
549 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
550 * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal})
551 * @param minIdle the minimum number of idle objects to have in the pool at any one time (see {@link #setMinIdle})
552 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject}
553 * method (see {@link #setTestOnBorrow})
554 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject}
555 * method (see {@link #setTestOnReturn})
556 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle
557 * objects
558 * for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
559 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction
560 * thread (if any) (see {@link #setNumTestsPerEvictionRun})
561 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before
562 * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis})
563 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any
564 * (see {@link #setTestWhileIdle})
565 * @since Pool 1.3
566 */
567 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction,
568 long maxWait, int maxIdle, int maxTotal, int minIdle, boolean testOnBorrow, boolean testOnReturn,
569 long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis,
570 boolean testWhileIdle) {
571 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, maxTotal, minIdle, testOnBorrow, testOnReturn,
572 timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle,
573 DEFAULT_LIFO);
574 }
575
576 /**
577 * Create a new <code>GenericKeyedObjectPool</code> using the specified values.
578 * @param factory the <code>KeyedPoolableObjectFactory</code> to use to create, validate, and destroy objects
579 * if not <code>null</code>
580 * @param maxActive the maximum number of objects that can be borrowed at one time
581 * (see {@link #setMaxActive})
582 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
583 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and
584 * <code>whenExhaustedAction</code> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
585 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
586 * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal})
587 * @param minIdle the minimum number of idle objects to have in the pool at any one time (see {@link #setMinIdle})
588 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject}
589 * method (see {@link #setTestOnBorrow})
590 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject}
591 * method (see {@link #setTestOnReturn})
592 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle
593 * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
594 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction
595 * thread (if any) (see {@link #setNumTestsPerEvictionRun})
596 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before
597 * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis})
598 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any
599 * (see {@link #setTestWhileIdle})
600 * @param lifo whether or not the pools behave as LIFO (last in first out) queues (see {@link #setLifo})
601 * @since Pool 1.4
602 */
603 public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction,
604 long maxWait, int maxIdle, int maxTotal, int minIdle, boolean testOnBorrow, boolean testOnReturn,
605 long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis,
606 boolean testWhileIdle, boolean lifo) {
607 _factory = factory;
608 _maxActive = maxActive;
609 _lifo = lifo;
610 switch (whenExhaustedAction) {
611 case WHEN_EXHAUSTED_BLOCK:
612 case WHEN_EXHAUSTED_FAIL:
613 case WHEN_EXHAUSTED_GROW:
614 _whenExhaustedAction = whenExhaustedAction;
615 break;
616 default:
617 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
618 }
619 _maxWait = maxWait;
620 _maxIdle = maxIdle;
621 _maxTotal = maxTotal;
622 _minIdle = minIdle;
623 _testOnBorrow = testOnBorrow;
624 _testOnReturn = testOnReturn;
625 _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
626 _numTestsPerEvictionRun = numTestsPerEvictionRun;
627 _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
628 _testWhileIdle = testWhileIdle;
629
630 _poolMap = new HashMap();
631 _poolList = new CursorableLinkedList();
632
633 startEvictor(_timeBetweenEvictionRunsMillis);
634 }
635
636 //--- public methods ---------------------------------------------
637
638 //--- configuration methods --------------------------------------
639
640 /**
641 * Returns the cap on the number of object instances allocated by the pool
642 * (checked out or idle), per key.
643 * A negative value indicates no limit.
644 *
645 * @return the cap on the number of active instances per key.
646 * @see #setMaxActive
647 */
648 public synchronized int getMaxActive() {
649 return _maxActive;
650 }
651
652 /**
653 * Sets the cap on the number of object instances managed by the pool per key.
654 * @param maxActive The cap on the number of object instances per key.
655 * Use a negative value for no limit.
656 *
657 * @see #getMaxActive
658 */
659 public synchronized void setMaxActive(int maxActive) {
660 _maxActive = maxActive;
661 allocate();
662 }
663
664 /**
665 * Returns the overall maximum number of objects (across pools) that can
666 * exist at one time. A negative value indicates no limit.
667 * @return the maximum number of instances in circulation at one time.
668 * @see #setMaxTotal
669 */
670 public synchronized int getMaxTotal() {
671 return _maxTotal;
672 }
673
674 /**
675 * Sets the cap on the total number of instances from all pools combined.
676 * When <code>maxTotal</code> is set to a
677 * positive value and {@link #borrowObject borrowObject} is invoked
678 * when at the limit with no idle instances available, an attempt is made to
679 * create room by clearing the oldest 15% of the elements from the keyed
680 * pools.
681 *
682 * @param maxTotal The cap on the total number of instances across pools.
683 * Use a negative value for no limit.
684 * @see #getMaxTotal
685 */
686 public synchronized void setMaxTotal(int maxTotal) {
687 _maxTotal = maxTotal;
688 allocate();
689 }
690
691 /**
692 * Returns the action to take when the {@link #borrowObject} method
693 * is invoked when the pool is exhausted (the maximum number
694 * of "active" objects has been reached).
695 *
696 * @return one of {@link #WHEN_EXHAUSTED_BLOCK},
697 * {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW}
698 * @see #setWhenExhaustedAction
699 */
700 public synchronized byte getWhenExhaustedAction() {
701 return _whenExhaustedAction;
702 }
703
704 /**
705 * Sets the action to take when the {@link #borrowObject} method
706 * is invoked when the pool is exhausted (the maximum number
707 * of "active" objects has been reached).
708 *
709 * @param whenExhaustedAction the action code, which must be one of
710 * {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL},
711 * or {@link #WHEN_EXHAUSTED_GROW}
712 * @see #getWhenExhaustedAction
713 */
714 public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) {
715 switch(whenExhaustedAction) {
716 case WHEN_EXHAUSTED_BLOCK:
717 case WHEN_EXHAUSTED_FAIL:
718 case WHEN_EXHAUSTED_GROW:
719 _whenExhaustedAction = whenExhaustedAction;
720 allocate();
721 break;
722 default:
723 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
724 }
725 }
726
727
728 /**
729 * Returns the maximum amount of time (in milliseconds) the
730 * {@link #borrowObject} method should block before throwing
731 * an exception when the pool is exhausted and the
732 * {@link #setWhenExhaustedAction "when exhausted" action} is
733 * {@link #WHEN_EXHAUSTED_BLOCK}.
734 *
735 * When less than or equal to 0, the {@link #borrowObject} method
736 * may block indefinitely.
737 *
738 * @return the maximum number of milliseconds borrowObject will block.
739 * @see #setMaxWait
740 * @see #setWhenExhaustedAction
741 * @see #WHEN_EXHAUSTED_BLOCK
742 */
743 public synchronized long getMaxWait() {
744 return _maxWait;
745 }
746
747 /**
748 * Sets the maximum amount of time (in milliseconds) the
749 * {@link #borrowObject} method should block before throwing
750 * an exception when the pool is exhausted and the
751 * {@link #setWhenExhaustedAction "when exhausted" action} is
752 * {@link #WHEN_EXHAUSTED_BLOCK}.
753 *
754 * When less than or equal to 0, the {@link #borrowObject} method
755 * may block indefinitely.
756 *
757 * @param maxWait the maximum number of milliseconds borrowObject will block or negative for indefinitely.
758 * @see #getMaxWait
759 * @see #setWhenExhaustedAction
760 * @see #WHEN_EXHAUSTED_BLOCK
761 */
762 public synchronized void setMaxWait(long maxWait) {
763 _maxWait = maxWait;
764 }
765
766 /**
767 * Returns the cap on the number of "idle" instances per key.
768 * @return the maximum number of "idle" instances that can be held
769 * in a given keyed pool.
770 * @see #setMaxIdle
771 */
772 public synchronized int getMaxIdle() {
773 return _maxIdle;
774 }
775
776 /**
777 * Sets the cap on the number of "idle" instances in the pool.
778 * If maxIdle is set too low on heavily loaded systems it is possible you
779 * will see objects being destroyed and almost immediately new objects
780 * being created. This is a result of the active threads momentarily
781 * returning objects faster than they are requesting them them, causing the
782 * number of idle objects to rise above maxIdle. The best value for maxIdle
783 * for heavily loaded system will vary but the default is a good starting
784 * point.
785 * @param maxIdle the maximum number of "idle" instances that can be held
786 * in a given keyed pool. Use a negative value for no limit.
787 * @see #getMaxIdle
788 * @see #DEFAULT_MAX_IDLE
789 */
790 public synchronized void setMaxIdle(int maxIdle) {
791 _maxIdle = maxIdle;
792 allocate();
793 }
794
795 /**
796 * Sets the minimum number of idle objects to maintain in each of the keyed
797 * pools. This setting has no effect unless
798 * <code>timeBetweenEvictionRunsMillis > 0</code> and attempts to ensure
799 * that each pool has the required minimum number of instances are only
800 * made during idle object eviction runs.
801 * @param poolSize - The minimum size of the each keyed pool
802 * @since Pool 1.3
803 * @see #getMinIdle
804 * @see #setTimeBetweenEvictionRunsMillis
805 */
806 public synchronized void setMinIdle(int poolSize) {
807 _minIdle = poolSize;
808 }
809
810 /**
811 * Returns the minimum number of idle objects to maintain in each of the keyed
812 * pools. This setting has no effect unless
813 * <code>timeBetweenEvictionRunsMillis > 0</code> and attempts to ensure
814 * that each pool has the required minimum number of instances are only
815 * made during idle object eviction runs.
816 * @return minimum size of the each keyed pool
817 * @since Pool 1.3
818 * @see #setTimeBetweenEvictionRunsMillis
819 */
820 public synchronized int getMinIdle() {
821 return _minIdle;
822 }
823
824 /**
825 * When <code>true</code>, objects will be
826 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
827 * before being returned by the {@link #borrowObject}
828 * method. If the object fails to validate,
829 * it will be dropped from the pool, and we will attempt
830 * to borrow another.
831 *
832 * @return <code>true</code> if objects are validated before being borrowed.
833 * @see #setTestOnBorrow
834 */
835 public boolean getTestOnBorrow() {
836 return _testOnBorrow;
837 }
838
839 /**
840 * When <code>true</code>, objects will be
841 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
842 * before being returned by the {@link #borrowObject}
843 * method. If the object fails to validate,
844 * it will be dropped from the pool, and we will attempt
845 * to borrow another.
846 *
847 * @param testOnBorrow whether object should be validated before being returned by borrowObject.
848 * @see #getTestOnBorrow
849 */
850 public void setTestOnBorrow(boolean testOnBorrow) {
851 _testOnBorrow = testOnBorrow;
852 }
853
854 /**
855 * When <code>true</code>, objects will be
856 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
857 * before being returned to the pool within the
858 * {@link #returnObject}.
859 *
860 * @return <code>true</code> when objects will be validated before being returned.
861 * @see #setTestOnReturn
862 */
863 public boolean getTestOnReturn() {
864 return _testOnReturn;
865 }
866
867 /**
868 * When <code>true</code>, objects will be
869 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
870 * before being returned to the pool within the
871 * {@link #returnObject}.
872 *
873 * @param testOnReturn <code>true</code> so objects will be validated before being returned.
874 * @see #getTestOnReturn
875 */
876 public void setTestOnReturn(boolean testOnReturn) {
877 _testOnReturn = testOnReturn;
878 }
879
880 /**
881 * Returns the number of milliseconds to sleep between runs of the
882 * idle object evictor thread.
883 * When non-positive, no idle object evictor thread will be
884 * run.
885 *
886 * @return milliseconds to sleep between evictor runs.
887 * @see #setTimeBetweenEvictionRunsMillis
888 */
889 public synchronized long getTimeBetweenEvictionRunsMillis() {
890 return _timeBetweenEvictionRunsMillis;
891 }
892
893 /**
894 * Sets the number of milliseconds to sleep between runs of the
895 * idle object evictor thread.
896 * When non-positive, no idle object evictor thread will be
897 * run.
898 *
899 * @param timeBetweenEvictionRunsMillis milliseconds to sleep between evictor runs.
900 * @see #getTimeBetweenEvictionRunsMillis
901 */
902 public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
903 _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
904 startEvictor(_timeBetweenEvictionRunsMillis);
905 }
906
907 /**
908 * Returns the max number of objects to examine during each run of the
909 * idle object evictor thread (if any).
910 *
911 * @return number of objects to examine each eviction run.
912 * @see #setNumTestsPerEvictionRun
913 * @see #setTimeBetweenEvictionRunsMillis
914 */
915 public synchronized int getNumTestsPerEvictionRun() {
916 return _numTestsPerEvictionRun;
917 }
918
919 /**
920 * Sets the max number of objects to examine during each run of the
921 * idle object evictor thread (if any).
922 * <p>
923 * When a negative value is supplied,
924 * <code>ceil({@link #getNumIdle()})/abs({@link #getNumTestsPerEvictionRun})</code>
925 * tests will be run. I.e., when the value is <code>-n</code>, roughly one <code>n</code>th of the
926 * idle objects will be tested per run. When the value is positive, the number of tests
927 * actually performed in each run will be the minimum of this value and the number of instances
928 * idle in the pools.
929 *
930 * @param numTestsPerEvictionRun number of objects to examine each eviction run.
931 * @see #setNumTestsPerEvictionRun
932 * @see #setTimeBetweenEvictionRunsMillis
933 */
934 public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
935 _numTestsPerEvictionRun = numTestsPerEvictionRun;
936 }
937
938 /**
939 * Returns the minimum amount of time an object may sit idle in the pool
940 * before it is eligible for eviction by the idle object evictor
941 * (if any).
942 *
943 * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction.
944 * @see #setMinEvictableIdleTimeMillis
945 * @see #setTimeBetweenEvictionRunsMillis
946 */
947 public synchronized long getMinEvictableIdleTimeMillis() {
948 return _minEvictableIdleTimeMillis;
949 }
950
951 /**
952 * Sets the minimum amount of time an object may sit idle in the pool
953 * before it is eligible for eviction by the idle object evictor
954 * (if any).
955 * When non-positive, no objects will be evicted from the pool
956 * due to idle time alone.
957 *
958 * @param minEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before
959 * it is eligible for eviction.
960 * @see #getMinEvictableIdleTimeMillis
961 * @see #setTimeBetweenEvictionRunsMillis
962 */
963 public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
964 _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
965 }
966
967 /**
968 * When <code>true</code>, objects will be
969 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
970 * by the idle object evictor (if any). If an object
971 * fails to validate, it will be dropped from the pool.
972 *
973 * @return <code>true</code> when objects are validated when borrowed.
974 * @see #setTestWhileIdle
975 * @see #setTimeBetweenEvictionRunsMillis
976 */
977 public synchronized boolean getTestWhileIdle() {
978 return _testWhileIdle;
979 }
980
981 /**
982 * When <code>true</code>, objects will be
983 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
984 * by the idle object evictor (if any). If an object
985 * fails to validate, it will be dropped from the pool.
986 *
987 * @param testWhileIdle <code>true</code> so objects are validated when borrowed.
988 * @see #getTestWhileIdle
989 * @see #setTimeBetweenEvictionRunsMillis
990 */
991 public synchronized void setTestWhileIdle(boolean testWhileIdle) {
992 _testWhileIdle = testWhileIdle;
993 }
994
995 /**
996 * Sets the configuration.
997 * @param conf the new configuration to use.
998 * @see GenericKeyedObjectPool.Config
999 */
1000 public synchronized void setConfig(GenericKeyedObjectPool.Config conf) {
1001 setMaxIdle(conf.maxIdle);
1002 setMaxActive(conf.maxActive);
1003 setMaxTotal(conf.maxTotal);
1004 setMinIdle(conf.minIdle);
1005 setMaxWait(conf.maxWait);
1006 setWhenExhaustedAction(conf.whenExhaustedAction);
1007 setTestOnBorrow(conf.testOnBorrow);
1008 setTestOnReturn(conf.testOnReturn);
1009 setTestWhileIdle(conf.testWhileIdle);
1010 setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun);
1011 setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
1012 setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
1013 }
1014
1015 /**
1016 * Whether or not the idle object pools act as LIFO queues. True means
1017 * that borrowObject returns the most recently used ("last in") idle object
1018 * in a pool (if there are idle instances available). False means that
1019 * the pools behave as FIFO queues - objects are taken from idle object
1020 * pools in the order that they are returned.
1021 *
1022 * @return <code>true</code> if the pools are configured to act as LIFO queues
1023 * @since 1.4
1024 */
1025 public synchronized boolean getLifo() {
1026 return _lifo;
1027 }
1028
1029 /**
1030 * Sets the LIFO property of the pools. True means that borrowObject returns
1031 * the most recently used ("last in") idle object in a pool (if there are
1032 * idle instances available). False means that the pools behave as FIFO
1033 * queues - objects are taken from idle object pools in the order that
1034 * they are returned.
1035 *
1036 * @param lifo the new value for the lifo property
1037 * @since 1.4
1038 */
1039 public synchronized void setLifo(boolean lifo) {
1040 this._lifo = lifo;
1041 }
1042
1043 //-- ObjectPool methods ------------------------------------------
1044
1045 /**
1046 * <p>Borrows an object from the keyed pool associated with the given key.</p>
1047 *
1048 * <p>If there is an idle instance available in the pool associated with the given key, then
1049 * either the most-recently returned (if {@link #getLifo() lifo} == true) or "oldest" (lifo == false)
1050 * instance sitting idle in the pool will be activated and returned. If activation fails, or
1051 * {@link #getTestOnBorrow() testOnBorrow} is set to true and validation fails, the instance is destroyed and the
1052 * next available instance is examined. This continues until either a valid instance is returned or there
1053 * are no more idle instances available.</p>
1054 *
1055 * <p>If there are no idle instances available in the pool associated with the given key, behavior
1056 * depends on the {@link #getMaxActive() maxActive}, {@link #getMaxTotal() maxTotal}, and (if applicable)
1057 * {@link #getWhenExhaustedAction() whenExhaustedAction} and {@link #getMaxWait() maxWait} properties. If the
1058 * number of instances checked out from the pool under the given key is less than <code>maxActive</code> and
1059 * the total number of instances in circulation (under all keys) is less than <code>maxTotal</code>, a new instance
1060 * is created, activated and (if applicable) validated and returned to the caller.</p>
1061 *
1062 * <p>If the associated keyed pool is exhausted (no available idle instances and no capacity to create new ones),
1063 * this method will either block ({@link #WHEN_EXHAUSTED_BLOCK}), throw a <code>NoSuchElementException</code>
1064 * ({@link #WHEN_EXHAUSTED_FAIL}), or grow ({@link #WHEN_EXHAUSTED_GROW} - ignoring maxActive, maxTotal properties).
1065 * The length of time that this method will block when <code>whenExhaustedAction == WHEN_EXHAUSTED_BLOCK</code>
1066 * is determined by the {@link #getMaxWait() maxWait} property.</p>
1067 *
1068 * <p>When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances
1069 * to become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads receive
1070 * available instances in request arrival order.</p>
1071 *
1072 * @param key pool key
1073 * @return object instance from the keyed pool
1074 * @throws NoSuchElementException if a keyed object instance cannot be returned.
1075 */
1076 public Object borrowObject(Object key) throws Exception {
1077 long starttime = System.currentTimeMillis();
1078 Latch latch = new Latch(key);
1079 byte whenExhaustedAction;
1080 long maxWait;
1081 synchronized (this) {
1082 // Get local copy of current config. Can't sync when used later as
1083 // it can result in a deadlock. Has the added advantage that config
1084 // is consistent for entire method execution
1085 whenExhaustedAction = _whenExhaustedAction;
1086 maxWait = _maxWait;
1087
1088 // Add this request to the queue
1089 _allocationQueue.add(latch);
1090
1091 // Work the allocation queue, allocating idle instances and
1092 // instance creation permits in request arrival order
1093 allocate();
1094 }
1095
1096 for(;;) {
1097 synchronized (this) {
1098 assertOpen();
1099 }
1100 // If no object was allocated
1101 if (null == latch.getPair()) {
1102 // Check to see if we were allowed to create one
1103 if (latch.mayCreate()) {
1104 // allow new object to be created
1105 } else {
1106 // the pool is exhausted
1107 switch(whenExhaustedAction) {
1108 case WHEN_EXHAUSTED_GROW:
1109 // allow new object to be created
1110 synchronized (this) {
1111 // Make sure allocate hasn't already assigned an object
1112 // in a different thread
1113 if (latch.getPair() == null) {
1114 _allocationQueue.remove(latch);
1115 latch.getPool().incrementInternalProcessingCount();
1116 }
1117 }
1118 break;
1119 case WHEN_EXHAUSTED_FAIL:
1120 synchronized (this) {
1121 // Make sure allocate hasn't already assigned an object
1122 // in a different thread
1123 if (latch.getPair() != null) {
1124 break;
1125 }
1126 _allocationQueue.remove(latch);
1127 }
1128 throw new NoSuchElementException("Pool exhausted");
1129 case WHEN_EXHAUSTED_BLOCK:
1130 try {
1131 synchronized (latch) {
1132 // Before we wait, make sure another thread didn't allocate us an object
1133 if (latch.getPair() == null) {
1134 if (maxWait <= 0) {
1135 latch.wait();
1136 } else {
1137 // this code may be executed again after a notify then continue cycle
1138 // so, need to calculate the amount of time to wait
1139 final long elapsed = (System.currentTimeMillis() - starttime);
1140 final long waitTime = maxWait - elapsed;
1141 if (waitTime > 0)
1142 {
1143 latch.wait(waitTime);
1144 }
1145 }
1146 } else {
1147 break;
1148 }
1149 }
1150 } catch(InterruptedException e) {
1151 Thread.currentThread().interrupt();
1152 throw e;
1153 }
1154 if (maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
1155 synchronized (this) {
1156 // Make sure allocate hasn't already assigned an object
1157 // in a different thread
1158 if (latch.getPair() == null) {
1159 _allocationQueue.remove(latch);
1160 } else {
1161 break;
1162 }
1163 }
1164 throw new NoSuchElementException("Timeout waiting for idle object");
1165 } else {
1166 continue; // keep looping
1167 }
1168 default:
1169 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction +
1170 " not recognized.");
1171 }
1172 }
1173 }
1174
1175 boolean newlyCreated = false;
1176 if (null == latch.getPair()) {
1177 try {
1178 Object obj = _factory.makeObject(key);
1179 latch.setPair(new ObjectTimestampPair(obj));
1180 newlyCreated = true;
1181 } finally {
1182 if (!newlyCreated) {
1183 // object cannot be created
1184 synchronized (this) {
1185 latch.getPool().decrementInternalProcessingCount();
1186 // No need to reset latch - about to throw exception
1187 allocate();
1188 }
1189 }
1190 }
1191 }
1192
1193 // activate & validate the object
1194 try {
1195 _factory.activateObject(key, latch.getPair().value);
1196 if (_testOnBorrow && !_factory.validateObject(key, latch.getPair().value)) {
1197 throw new Exception("ValidateObject failed");
1198 }
1199 synchronized (this) {
1200 latch.getPool().decrementInternalProcessingCount();
1201 latch.getPool().incrementActiveCount();
1202 }
1203 return latch.getPair().value;
1204 } catch (Throwable e) {
1205 // object cannot be activated or is invalid
1206 try {
1207 _factory.destroyObject(key, latch.getPair().value);
1208 } catch (Throwable e2) {
1209 // cannot destroy broken object
1210 }
1211 synchronized (this) {
1212 latch.getPool().decrementInternalProcessingCount();
1213 latch.reset();
1214 _allocationQueue.add(0, latch);
1215 allocate();
1216 }
1217 if (newlyCreated) {
1218 throw new NoSuchElementException(
1219 "Could not create a validated object, cause: " +
1220 e.getMessage());
1221 }
1222 else {
1223 continue; // keep looping
1224 }
1225 }
1226 }
1227 }
1228
1229 /**
1230 * Allocate available instances to latches in the allocation queue. Then
1231 * set _mayCreate to true for as many additional latches remaining in queue
1232 * as _maxActive allows for each key.
1233 */
1234 private void allocate() {
1235 boolean clearOldest = false;
1236
1237 synchronized (this) {
1238 if (isClosed()) return;
1239
1240 Iterator allocationQueueIter = _allocationQueue.iterator();
1241
1242 while (allocationQueueIter.hasNext()) {
1243 // First use any objects in the pool to clear the queue
1244 Latch latch = (Latch) allocationQueueIter.next();
1245 ObjectQueue pool = (ObjectQueue)(_poolMap.get(latch.getkey()));
1246 if (null == pool) {
1247 pool = new ObjectQueue();
1248 _poolMap.put(latch.getkey(), pool);
1249 _poolList.add(latch.getkey());
1250 }
1251 latch.setPool(pool);
1252 if (!pool.queue.isEmpty()) {
1253 allocationQueueIter.remove();
1254 latch.setPair(
1255 (ObjectTimestampPair) pool.queue.removeFirst());
1256 pool.incrementInternalProcessingCount();
1257 _totalIdle--;
1258 synchronized (latch) {
1259 latch.notify();
1260 }
1261 // Next item in queue
1262 continue;
1263 }
1264
1265 // If there is a totalMaxActive and we are at the limit then
1266 // we have to make room
1267 if ((_maxTotal > 0) &&
1268 (_totalActive + _totalIdle + _totalInternalProcessing >= _maxTotal)) {
1269 clearOldest = true;
1270 break;
1271 }
1272
1273 // Second utilise any spare capacity to create new objects
1274 if ((_maxActive < 0 || pool.activeCount + pool.internalProcessingCount < _maxActive) &&
1275 (_maxTotal < 0 || _totalActive + _totalIdle + _totalInternalProcessing < _maxTotal)) {
1276 // allow new object to be created
1277 allocationQueueIter.remove();
1278 latch.setMayCreate(true);
1279 pool.incrementInternalProcessingCount();
1280 synchronized (latch) {
1281 latch.notify();
1282 }
1283 // Next item in queue
1284 continue;
1285 }
1286
1287 // If there is no per-key limit and we reach this point we
1288 // must have allocated all the objects we possibly can and there
1289 // is no point looking at the rest of the allocation queue
1290 if (_maxActive < 0) {
1291 break;
1292 }
1293 }
1294 }
1295
1296 if (clearOldest) {
1297 /* Clear oldest calls factory methods so it must be called from
1298 * outside the sync block.
1299 * It also needs to be outside the sync block as it calls
1300 * allocate(). If called inside the sync block, the call to
1301 * allocate() would be able to enter the sync block (since the
1302 * thread already has the lock) which may have unexpected,
1303 * unpleasant results.
1304 */
1305 clearOldest();
1306 }
1307 }
1308
1309 /**
1310 * Clears any objects sitting idle in the pool by removing them from the
1311 * idle instance pool and then invoking the configured
1312 * {@link KeyedPoolableObjectFactory#destroyObject(Object, Object)} method on
1313 * each idle instance.
1314 *
1315 * <p> Implementation notes:
1316 * <ul><li>This method does not destroy or effect in any way instances that are
1317 * checked out when it is invoked.</li>
1318 * <li>Invoking this method does not prevent objects being
1319 * returned to the idle instance pool, even during its execution. It locks
1320 * the pool only during instance removal. Additional instances may be returned
1321 * while removed items are being destroyed.</li></ul></p>
1322 */
1323 public void clear() {
1324 Map toDestroy = new HashMap();
1325 synchronized (this) {
1326 for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) {
1327 Object key = it.next();
1328 ObjectQueue pool = (ObjectQueue)_poolMap.get(key);
1329 // Copy objects to new list so pool.queue can be cleared inside
1330 // the sync
1331 List objects = new ArrayList();
1332 objects.addAll(pool.queue);
1333 toDestroy.put(key, objects);
1334 it.remove();
1335 _poolList.remove(key);
1336 _totalIdle = _totalIdle - pool.queue.size();
1337 _totalInternalProcessing =
1338 _totalInternalProcessing + pool.queue.size();
1339 pool.queue.clear();
1340 }
1341 }
1342 destroy(toDestroy);
1343 }
1344
1345 /**
1346 * Clears oldest 15% of objects in pool. The method sorts the
1347 * objects into a TreeMap and then iterates the first 15% for removal.
1348 *
1349 * @since Pool 1.3
1350 */
1351 public void clearOldest() {
1352 // Map of objects to destroy my key
1353 final Map toDestroy = new HashMap();
1354
1355 // build sorted map of idle objects
1356 final Map map = new TreeMap();
1357 synchronized (this) {
1358 for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) {
1359 final Object key = keyiter.next();
1360 final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue;
1361 for (Iterator it = list.iterator(); it.hasNext();) {
1362 // each item into the map uses the objectimestamppair object
1363 // as the key. It then gets sorted based on the timstamp field
1364 // each value in the map is the parent list it belongs in.
1365 map.put(it.next(), key);
1366 }
1367 }
1368
1369 // Now iterate created map and kill the first 15% plus one to account for zero
1370 Set setPairKeys = map.entrySet();
1371 int itemsToRemove = ((int) (map.size() * 0.15)) + 1;
1372
1373 Iterator iter = setPairKeys.iterator();
1374 while (iter.hasNext() && itemsToRemove > 0) {
1375 Map.Entry entry = (Map.Entry) iter.next();
1376 // kind of backwards on naming. In the map, each key is the objecttimestamppair
1377 // because it has the ordering with the timestamp value. Each value that the
1378 // key references is the key of the list it belongs to.
1379 Object key = entry.getValue();
1380 ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey();
1381 final CursorableLinkedList list =
1382 ((ObjectQueue)(_poolMap.get(key))).queue;
1383 list.remove(pairTimeStamp);
1384
1385 if (toDestroy.containsKey(key)) {
1386 ((List)toDestroy.get(key)).add(pairTimeStamp);
1387 } else {
1388 List listForKey = new ArrayList();
1389 listForKey.add(pairTimeStamp);
1390 toDestroy.put(key, listForKey);
1391 }
1392 // if that was the last object for that key, drop that pool
1393 if (list.isEmpty()) {
1394 _poolMap.remove(key);
1395 _poolList.remove(key);
1396 }
1397 _totalIdle--;
1398 _totalInternalProcessing++;
1399 itemsToRemove--;
1400 }
1401
1402 }
1403 destroy(toDestroy);
1404 }
1405
1406 /**
1407 * Clears the specified pool, removing all pooled instances corresponding to the given <code>key</code>.
1408 *
1409 * @param key the key to clear
1410 */
1411 public void clear(Object key) {
1412 Map toDestroy = new HashMap();
1413
1414 final ObjectQueue pool;
1415 synchronized (this) {
1416 pool = (ObjectQueue)(_poolMap.remove(key));
1417 if (pool == null) {
1418 return;
1419 } else {
1420 _poolList.remove(key);
1421 }
1422 // Copy objects to new list so pool.queue can be cleared inside
1423 // the sync
1424 List objects = new ArrayList();
1425 objects.addAll(pool.queue);
1426 toDestroy.put(key, objects);
1427 _totalIdle = _totalIdle - pool.queue.size();
1428 _totalInternalProcessing =
1429 _totalInternalProcessing + pool.queue.size();
1430 pool.queue.clear();
1431 }
1432 destroy(toDestroy);
1433 }
1434
1435 /**
1436 * Assuming Map<Object,Collection<ObjectTimestampPair>>, destroy all
1437 * ObjectTimestampPair.value
1438 *
1439 * @param m Map containing keyed pools to clear
1440 */
1441 private void destroy(Map m) {
1442 for (Iterator keys = m.keySet().iterator(); keys.hasNext();) {
1443 Object key = keys.next();
1444 Collection c = (Collection) m.get(key);
1445 for (Iterator it = c.iterator(); it.hasNext();) {
1446 try {
1447 _factory.destroyObject(
1448 key,((ObjectTimestampPair)(it.next())).value);
1449 } catch(Exception e) {
1450 // ignore error, keep destroying the rest
1451 } finally {
1452 synchronized(this) {
1453 _totalInternalProcessing--;
1454 allocate();
1455 }
1456 }
1457 }
1458
1459 }
1460 }
1461
1462 /**
1463 * Returns the total number of instances current borrowed from this pool but not yet returned.
1464 *
1465 * @return the total number of instances currently borrowed from this pool
1466 */
1467 public synchronized int getNumActive() {
1468 return _totalActive;
1469 }
1470
1471 /**
1472 * Returns the total number of instances currently idle in this pool.
1473 *
1474 * @return the total number of instances currently idle in this pool
1475 */
1476 public synchronized int getNumIdle() {
1477 return _totalIdle;
1478 }
1479
1480 /**
1481 * Returns the number of instances currently borrowed from but not yet returned
1482 * to the pool corresponding to the given <code>key</code>.
1483 *
1484 * @param key the key to query
1485 * @return the number of instances corresponding to the given <code>key</code> currently borrowed in this pool
1486 */
1487 public synchronized int getNumActive(Object key) {
1488 final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key));
1489 return pool != null ? pool.activeCount : 0;
1490 }
1491
1492 /**
1493 * Returns the number of instances corresponding to the given <code>key</code> currently idle in this pool.
1494 *
1495 * @param key the key to query
1496 * @return the number of instances corresponding to the given <code>key</code> currently idle in this pool
1497 */
1498 public synchronized int getNumIdle(Object key) {
1499 final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key));
1500 return pool != null ? pool.queue.size() : 0;
1501 }
1502
1503 /**
1504 * <p>Returns an object to a keyed pool.</p>
1505 *
1506 * <p>For the pool to function correctly, the object instance <strong>must</strong> have been borrowed
1507 * from the pool (under the same key) and not yet returned. Repeated <code>returnObject</code> calls on
1508 * the same object/key pair (with no <code>borrowObject</code> calls in between) will result in multiple
1509 * references to the object in the idle instance pool.</p>
1510 *
1511 * <p>If {@link #getMaxIdle() maxIdle} is set to a positive value and the number of idle instances under the given
1512 * key has reached this value, the returning instance is destroyed.</p>
1513 *
1514 * <p>If {@link #getTestOnReturn() testOnReturn} == true, the returning instance is validated before being returned
1515 * to the idle instance pool under the given key. In this case, if validation fails, the instance is destroyed.</p>
1516 *
1517 * @param key pool key
1518 * @param obj instance to return to the keyed pool
1519 * @throws Exception
1520 */
1521 public void returnObject(Object key, Object obj) throws Exception {
1522 try {
1523 addObjectToPool(key, obj, true);
1524 } catch (Exception e) {
1525 if (_factory != null) {
1526 try {
1527 _factory.destroyObject(key, obj);
1528 } catch (Exception e2) {
1529 // swallowed
1530 }
1531 // TODO: Correctness here depends on control in addObjectToPool.
1532 // These two methods should be refactored, removing the
1533 // "behavior flag", decrementNumActive, from addObjectToPool.
1534 ObjectQueue pool = (ObjectQueue) (_poolMap.get(key));
1535 if (pool != null) {
1536 synchronized(this) {
1537 pool.decrementActiveCount();
1538 allocate();
1539 }
1540 }
1541 }
1542 }
1543 }
1544
1545 /**
1546 * <p>Adds an object to the keyed pool.</p>
1547 *
1548 * <p>Validates the object if testOnReturn == true and passivates it before returning it to the pool.
1549 * if validation or passivation fails, or maxIdle is set and there is no room in the pool, the instance
1550 * is destroyed.</p>
1551 *
1552 * <p>Calls {@link #allocate()} on successful completion</p>
1553 *
1554 * @param key pool key
1555 * @param obj instance to add to the keyed pool
1556 * @param decrementNumActive whether or not to decrement the active count associated with the keyed pool
1557 * @throws Exception
1558 */
1559 private void addObjectToPool(Object key, Object obj,
1560 boolean decrementNumActive) throws Exception {
1561
1562 // if we need to validate this object, do so
1563 boolean success = true; // whether or not this object passed validation
1564 if (_testOnReturn && !_factory.validateObject(key, obj)) {
1565 success = false;
1566 } else {
1567 _factory.passivateObject(key, obj);
1568 }
1569
1570 boolean shouldDestroy = !success;
1571 ObjectQueue pool;
1572
1573 // Add instance to pool if there is room and it has passed validation
1574 // (if testOnreturn is set)
1575 synchronized (this) {
1576 // grab the pool (list) of objects associated with the given key
1577 pool = (ObjectQueue) (_poolMap.get(key));
1578 // if it doesn't exist, create it
1579 if (null == pool) {
1580 pool = new ObjectQueue();
1581 _poolMap.put(key, pool);
1582 _poolList.add(key);
1583 }
1584 if (isClosed()) {
1585 shouldDestroy = true;
1586 } else {
1587 // if there's no space in the pool, flag the object for destruction
1588 // else if we passivated successfully, return it to the pool
1589 if (_maxIdle >= 0 && (pool.queue.size() >= _maxIdle)) {
1590 shouldDestroy = true;
1591 } else if (success) {
1592 // borrowObject always takes the first element from the queue,
1593 // so for LIFO, push on top, FIFO add to end
1594 if (_lifo) {
1595 pool.queue.addFirst(new ObjectTimestampPair(obj));
1596 } else {
1597 pool.queue.addLast(new ObjectTimestampPair(obj));
1598 }
1599 _totalIdle++;
1600 if (decrementNumActive) {
1601 pool.decrementActiveCount();
1602 }
1603 allocate();
1604 }
1605 }
1606 }
1607
1608 // Destroy the instance if necessary
1609 if (shouldDestroy) {
1610 try {
1611 _factory.destroyObject(key, obj);
1612 } catch(Exception e) {
1613 // ignored?
1614 }
1615 // Decrement active count *after* destroy if applicable
1616 if (decrementNumActive) {
1617 synchronized(this) {
1618 pool.decrementActiveCount();
1619 allocate();
1620 }
1621 }
1622 }
1623 }
1624
1625 /**
1626 * <p>Invalidates the object instance associated with the given key. Decrements the active count
1627 * associated with the given keyed pool and destroys the instance.</p>
1628 *
1629 * @param key pool key
1630 * @param obj instance to invalidate
1631 * @throws Exception if an exception occurs destroying the object
1632 */
1633 public void invalidateObject(Object key, Object obj) throws Exception {
1634 try {
1635 _factory.destroyObject(key, obj);
1636 } finally {
1637 synchronized (this) {
1638 ObjectQueue pool = (ObjectQueue) (_poolMap.get(key));
1639 if (null == pool) {
1640 pool = new ObjectQueue();
1641 _poolMap.put(key, pool);
1642 _poolList.add(key);
1643 }
1644 pool.decrementActiveCount();
1645 allocate(); // _totalActive has changed
1646 }
1647 }
1648 }
1649
1650 /**
1651 * Create an object using the {@link KeyedPoolableObjectFactory#makeObject factory},
1652 * passivate it, and then place it in the idle object pool.
1653 * <code>addObject</code> is useful for "pre-loading" a pool with idle objects.
1654 *
1655 * @param key the key a new instance should be added to
1656 * @throws Exception when {@link KeyedPoolableObjectFactory#makeObject} fails.
1657 * @throws IllegalStateException when no {@link #setFactory factory} has been set or after {@link #close} has been
1658 * called on this pool.
1659 */
1660 public void addObject(Object key) throws Exception {
1661 assertOpen();
1662 if (_factory == null) {
1663 throw new IllegalStateException("Cannot add objects without a factory.");
1664 }
1665 Object obj = _factory.makeObject(key);
1666 try {
1667 assertOpen();
1668 addObjectToPool(key, obj, false);
1669 } catch (IllegalStateException ex) { // Pool closed
1670 try {
1671 _factory.destroyObject(key, obj);
1672 } catch (Exception ex2) {
1673 // swallow
1674 }
1675 throw ex;
1676 }
1677 }
1678
1679 /**
1680 * Registers a key for pool control.
1681 *
1682 * If <code>populateImmediately</code> is <code>true</code> and
1683 * <code>minIdle > 0,</code> the pool under the given key will be
1684 * populated immediately with <code>minIdle</code> idle instances.
1685 *
1686 * @param key - The key to register for pool control.
1687 * @param populateImmediately - If this is <code>true</code>, the pool
1688 * will be populated immediately.
1689 * @since Pool 1.3
1690 */
1691 public synchronized void preparePool(Object key, boolean populateImmediately) {
1692 ObjectQueue pool = (ObjectQueue)(_poolMap.get(key));
1693 if (null == pool) {
1694 pool = new ObjectQueue();
1695 _poolMap.put(key,pool);
1696 _poolList.add(key);
1697 }
1698
1699 if (populateImmediately) {
1700 try {
1701 // Create the pooled objects
1702 ensureMinIdle(key);
1703 }
1704 catch (Exception e) {
1705 //Do nothing
1706 }
1707 }
1708 }
1709
1710 /**
1711 * Closes the keyed object pool. Once the pool is closed, {@link #borrowObject(Object)}
1712 * will fail with IllegalStateException, but {@link #returnObject(Object, Object)} and
1713 * {@link #invalidateObject(Object, Object)} will continue to work. This method does not
1714 * {@link #clear()} the pool. The method is idempotent - that is, it is OK to call it on a closed
1715 * pool.
1716 *
1717 * @throws Exception
1718 */
1719 public void close() throws Exception {
1720 super.close();
1721 synchronized (this) {
1722 clear();
1723 if (null != _evictionCursor) {
1724 _evictionCursor.close();
1725 _evictionCursor = null;
1726 }
1727 if (null != _evictionKeyCursor) {
1728 _evictionKeyCursor.close();
1729 _evictionKeyCursor = null;
1730 }
1731 startEvictor(-1L);
1732 }
1733 }
1734
1735 /**
1736 * <p>Sets the keyed poolable object factory associated with this pool.</p>
1737 *
1738 * <p>If this method is called when objects are checked out of any of the keyed pools,
1739 * an IllegalStateException is thrown. Calling this method also has the side effect of
1740 * destroying any idle instances in existing keyed pools.</p>
1741 *
1742 * @param factory KeyedPoolableObjectFactory to use when creating keyed object pool instances
1743 * @throws IllegalStateException if there are active (checked out) instances associated with this keyed object pool
1744 */
1745 public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException {
1746 Map toDestroy = new HashMap();
1747 synchronized (this) {
1748 assertOpen();
1749 if (0 < getNumActive()) {
1750 throw new IllegalStateException("Objects are already active");
1751 } else {
1752 for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) {
1753 Object key = it.next();
1754 ObjectQueue pool = (ObjectQueue)_poolMap.get(key);
1755 if (pool != null) {
1756 // Copy objects to new list so pool.queue can be cleared
1757 // inside the sync
1758 List objects = new ArrayList();
1759 objects.addAll(pool.queue);
1760 toDestroy.put(key, objects);
1761 it.remove();
1762 _poolList.remove(key);
1763 _totalIdle = _totalIdle - pool.queue.size();
1764 _totalInternalProcessing =
1765 _totalInternalProcessing + pool.queue.size();
1766 pool.queue.clear();
1767 }
1768 }
1769 _factory = factory;
1770 }
1771 }
1772 destroy(toDestroy);
1773 }
1774
1775 /**
1776 * <p>Perform <code>numTests</code> idle object eviction tests, evicting
1777 * examined objects that meet the criteria for eviction. If
1778 * <code>testWhileIdle</code> is true, examined objects are validated
1779 * when visited (and removed if invalid); otherwise only objects that
1780 * have been idle for more than <code>minEvicableIdletimeMillis</code>
1781 * are removed.</p>
1782 *
1783 * <p>Successive activations of this method examine objects in keyed pools
1784 * in sequence, cycling through the keys and examining objects in
1785 * oldest-to-youngest order within the keyed pools.</p>
1786 *
1787 * @throws Exception when there is a problem evicting idle objects.
1788 */
1789 public void evict() throws Exception {
1790 Object key = null;
1791 boolean testWhileIdle;
1792 long minEvictableIdleTimeMillis;
1793
1794 synchronized (this) {
1795 // Get local copy of current config. Can't sync when used later as
1796 // it can result in a deadlock. Has the added advantage that config
1797 // is consistent for entire method execution
1798 testWhileIdle = _testWhileIdle;
1799 minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis;
1800
1801 // Initialize key to last key value
1802 if (_evictionKeyCursor != null &&
1803 _evictionKeyCursor._lastReturned != null) {
1804 key = _evictionKeyCursor._lastReturned.value();
1805 }
1806 }
1807
1808 for (int i=0, m=getNumTests(); i<m; i++) {
1809 final ObjectTimestampPair pair;
1810 synchronized (this) {
1811 // make sure pool map is not empty; otherwise do nothing
1812 if (_poolMap == null || _poolMap.size() == 0) {
1813 continue;
1814 }
1815
1816 // if we don't have a key cursor, then create one
1817 if (null == _evictionKeyCursor) {
1818 resetEvictionKeyCursor();
1819 key = null;
1820 }
1821
1822 // if we don't have an object cursor, create one
1823 if (null == _evictionCursor) {
1824 // if the _evictionKeyCursor has a next value, use this key
1825 if (_evictionKeyCursor.hasNext()) {
1826 key = _evictionKeyCursor.next();
1827 resetEvictionObjectCursor(key);
1828 } else {
1829 // Reset the key cursor and try again
1830 resetEvictionKeyCursor();
1831 if (_evictionKeyCursor != null) {
1832 if (_evictionKeyCursor.hasNext()) {
1833 key = _evictionKeyCursor.next();
1834 resetEvictionObjectCursor(key);
1835 }
1836 }
1837 }
1838 }
1839
1840 if (_evictionCursor == null) {
1841 continue; // should never happen; do nothing
1842 }
1843
1844 // If eviction cursor is exhausted, try to move
1845 // to the next key and reset
1846 if ((_lifo && !_evictionCursor.hasPrevious()) ||
1847 (!_lifo && !_evictionCursor.hasNext())) {
1848 if (_evictionKeyCursor != null) {
1849 if (_evictionKeyCursor.hasNext()) {
1850 key = _evictionKeyCursor.next();
1851 resetEvictionObjectCursor(key);
1852 } else { // Need to reset Key cursor
1853 resetEvictionKeyCursor();
1854 if (_evictionKeyCursor != null) {
1855 if (_evictionKeyCursor.hasNext()) {
1856 key = _evictionKeyCursor.next();
1857 resetEvictionObjectCursor(key);
1858 }
1859 }
1860 }
1861 }
1862 }
1863
1864 if ((_lifo && !_evictionCursor.hasPrevious()) ||
1865 (!_lifo && !_evictionCursor.hasNext())) {
1866 continue; // reset failed, do nothing
1867 }
1868
1869 // if LIFO and the _evictionCursor has a previous object,
1870 // or FIFO and _evictionCursor has a next object, test it
1871 pair = _lifo ?
1872 (ObjectTimestampPair) _evictionCursor.previous() :
1873 (ObjectTimestampPair) _evictionCursor.next();
1874 _evictionCursor.remove();
1875 _totalIdle--;
1876 _totalInternalProcessing++;
1877 }
1878
1879 boolean removeObject=false;
1880 if ((minEvictableIdleTimeMillis > 0) &&
1881 (System.currentTimeMillis() - pair.tstamp >
1882 minEvictableIdleTimeMillis)) {
1883 removeObject=true;
1884 }
1885 if (testWhileIdle && removeObject == false) {
1886 boolean active = false;
1887 try {
1888 _factory.activateObject(key,pair.value);
1889 active = true;
1890 } catch(Exception e) {
1891 removeObject=true;
1892 }
1893 if (active) {
1894 if (!_factory.validateObject(key,pair.value)) {
1895 removeObject=true;
1896 } else {
1897 try {
1898 _factory.passivateObject(key,pair.value);
1899 } catch(Exception e) {
1900 removeObject=true;
1901 }
1902 }
1903 }
1904 }
1905
1906 if (removeObject) {
1907 try {
1908 _factory.destroyObject(key, pair.value);
1909 } catch(Exception e) {
1910 // ignored
1911 } finally {
1912 // Do not remove the key from the _poolList or _poolmap,
1913 // even if the list stored in the _poolMap for this key is
1914 // empty when minIdle > 0.
1915 //
1916 // Otherwise if it was the last object for that key,
1917 // drop that pool
1918 if (_minIdle == 0) {
1919 synchronized (this) {
1920 ObjectQueue objectQueue =
1921 (ObjectQueue)_poolMap.get(key);
1922 if (objectQueue != null &&
1923 objectQueue.queue.isEmpty()) {
1924 _poolMap.remove(key);
1925 _poolList.remove(key);
1926 }
1927 }
1928 }
1929 }
1930 }
1931 synchronized (this) {
1932 if (!removeObject) {
1933 _evictionCursor.add(pair);
1934 _totalIdle++;
1935 if (_lifo) {
1936 // Skip over the element we just added back
1937 _evictionCursor.previous();
1938 }
1939 }
1940 _totalInternalProcessing--;
1941 }
1942 }
1943 }
1944
1945 /**
1946 * Resets the eviction key cursor and closes any
1947 * associated eviction object cursor
1948 */
1949 private void resetEvictionKeyCursor() {
1950 if (_evictionKeyCursor != null) {
1951 _evictionKeyCursor.close();
1952 }
1953 _evictionKeyCursor = _poolList.cursor();
1954 if (null != _evictionCursor) {
1955 _evictionCursor.close();
1956 _evictionCursor = null;
1957 }
1958 }
1959
1960 /**
1961 * Resets the eviction object cursor for the given key
1962 *
1963 * @param key eviction key
1964 */
1965 private void resetEvictionObjectCursor(Object key) {
1966 if (_evictionCursor != null) {
1967 _evictionCursor.close();
1968 }
1969 if (_poolMap == null) {
1970 return;
1971 }
1972 ObjectQueue pool = (ObjectQueue) (_poolMap.get(key));
1973 if (pool != null) {
1974 CursorableLinkedList queue = pool.queue;
1975 _evictionCursor = queue.cursor(_lifo ? queue.size() : 0);
1976 }
1977 }
1978
1979 /**
1980 * Iterates through all the known keys and creates any necessary objects to maintain
1981 * the minimum level of pooled objects.
1982 * @see #getMinIdle
1983 * @see #setMinIdle
1984 * @throws Exception If there was an error whilst creating the pooled objects.
1985 */
1986 private void ensureMinIdle() throws Exception {
1987 //Check if should sustain the pool
1988 if (_minIdle > 0) {
1989 Object[] keysCopy;
1990 synchronized(this) {
1991 // Get the current set of keys
1992 keysCopy = _poolMap.keySet().toArray();
1993 }
1994
1995 // Loop through all elements in _poolList
1996 // Find out the total number of max active and max idle for that class
1997 // If the number is less than the minIdle, do creation loop to boost numbers
1998 for (int i=0; i < keysCopy.length; i++) {
1999 //Get the next key to process
2000 ensureMinIdle(keysCopy[i]);
2001 }
2002 }
2003 }
2004
2005 /**
2006 * Re-creates any needed objects to maintain the minimum levels of
2007 * pooled objects for the specified key.
2008 *
2009 * This method uses {@link #calculateDefecit} to calculate the number
2010 * of objects to be created. {@link #calculateDefecit} can be overridden to
2011 * provide a different method of calculating the number of objects to be
2012 * created.
2013 * @param key The key to process
2014 * @throws Exception If there was an error whilst creating the pooled objects
2015 */
2016 private void ensureMinIdle(Object key) throws Exception {
2017 // Calculate current pool objects
2018 ObjectQueue pool;
2019 synchronized(this) {
2020 pool = (ObjectQueue)(_poolMap.get(key));
2021 }
2022 if (pool == null) {
2023 return;
2024 }
2025
2026 // this method isn't synchronized so the
2027 // calculateDeficit is done at the beginning
2028 // as a loop limit and a second time inside the loop
2029 // to stop when another thread already returned the
2030 // needed objects
2031 int objectDeficit = calculateDefecit(pool, false);
2032
2033 for (int i = 0; i < objectDeficit && calculateDefecit(pool, true) > 0; i++) {
2034 try {
2035 addObject(key);
2036 } finally {
2037 synchronized (this) {
2038 pool.decrementInternalProcessingCount();
2039 allocate();
2040 }
2041 }
2042 }
2043 }
2044
2045 //--- non-public methods ----------------------------------------
2046
2047 /**
2048 * Start the eviction thread or service, or when
2049 * <code>delay</code> is non-positive, stop it
2050 * if it is already running.
2051 *
2052 * @param delay milliseconds between evictor runs.
2053 */
2054 protected synchronized void startEvictor(long delay) {
2055 if (null != _evictor) {
2056 EvictionTimer.cancel(_evictor);
2057 _evictor = null;
2058 }
2059 if (delay > 0) {
2060 _evictor = new Evictor();
2061 EvictionTimer.schedule(_evictor, delay, delay);
2062 }
2063 }
2064
2065 /**
2066 * Returns pool info including {@link #getNumActive()}, {@link #getNumIdle()}
2067 * and currently defined keys.
2068 *
2069 * @return string containing debug information
2070 */
2071 synchronized String debugInfo() {
2072 StringBuffer buf = new StringBuffer();
2073 buf.append("Active: ").append(getNumActive()).append("\n");
2074 buf.append("Idle: ").append(getNumIdle()).append("\n");
2075 Iterator it = _poolMap.keySet().iterator();
2076 while (it.hasNext()) {
2077 Object key = it.next();
2078 buf.append("\t").append(key).append(" ").append(_poolMap.get(key)).append("\n");
2079 }
2080 return buf.toString();
2081 }
2082
2083 /**
2084 * Returns the number of tests to be performed in an Evictor run,
2085 * based on the current values of <code>_numTestsPerEvictionRun</code>
2086 * and <code>_totalIdle</code>.
2087 *
2088 * @see #setNumTestsPerEvictionRun
2089 * @return the number of tests for the Evictor to run
2090 */
2091 private synchronized int getNumTests() {
2092 if (_numTestsPerEvictionRun >= 0) {
2093 return Math.min(_numTestsPerEvictionRun, _totalIdle);
2094 } else {
2095 return(int)(Math.ceil(_totalIdle/Math.abs((double)_numTestsPerEvictionRun)));
2096 }
2097 }
2098
2099 /**
2100 * This returns the number of objects to create during the pool
2101 * sustain cycle. This will ensure that the minimum number of idle
2102 * instances is maintained without going past the maxActive value.
2103 *
2104 * @param pool the ObjectPool to calculate the deficit for
2105 * @param incrementInternal - Should the count of objects currently under
2106 * some form of internal processing be
2107 * incremented?
2108 * @return The number of objects to be created
2109 */
2110 private synchronized int calculateDefecit(ObjectQueue pool,
2111 boolean incrementInternal) {
2112 int objectDefecit = 0;
2113
2114 //Calculate no of objects needed to be created, in order to have
2115 //the number of pooled objects < maxActive();
2116 objectDefecit = getMinIdle() - pool.queue.size();
2117 if (getMaxActive() > 0) {
2118 int growLimit = Math.max(0, getMaxActive() - pool.activeCount - pool.queue.size() - pool.internalProcessingCount);
2119 objectDefecit = Math.min(objectDefecit, growLimit);
2120 }
2121
2122 // Take the maxTotal limit into account
2123 if (getMaxTotal() > 0) {
2124 int growLimit = Math.max(0, getMaxTotal() - getNumActive() - getNumIdle() - _totalInternalProcessing);
2125 objectDefecit = Math.min(objectDefecit, growLimit);
2126 }
2127
2128 if (incrementInternal && objectDefecit > 0) {
2129 pool.incrementInternalProcessingCount();
2130 }
2131 return objectDefecit;
2132 }
2133
2134 //--- inner classes ----------------------------------------------
2135
2136 /**
2137 * A "struct" that keeps additional information about the actual queue of pooled objects.
2138 */
2139 private class ObjectQueue {
2140 /** Number of instances checked out to clients from this queue */
2141 private int activeCount = 0;
2142
2143 /** Idle instance queue */
2144 private final CursorableLinkedList queue = new CursorableLinkedList();
2145
2146 /** Number of instances in process of being created */
2147 private int internalProcessingCount = 0;
2148
2149 /** Increment the active count for this queue */
2150 void incrementActiveCount() {
2151 synchronized (GenericKeyedObjectPool.this) {
2152 _totalActive++;
2153 }
2154 activeCount++;
2155 }
2156
2157 /** Decrement the active count for this queue */
2158 void decrementActiveCount() {
2159 synchronized (GenericKeyedObjectPool.this) {
2160 _totalActive--;
2161 }
2162 if (activeCount > 0) {
2163 activeCount--;
2164 }
2165 }
2166
2167 /** Record the fact that one more instance is queued for creation */
2168 void incrementInternalProcessingCount() {
2169 synchronized (GenericKeyedObjectPool.this) {
2170 _totalInternalProcessing++;
2171 }
2172 internalProcessingCount++;
2173 }
2174
2175 /** Decrement the number of instances in process of being created */
2176 void decrementInternalProcessingCount() {
2177 synchronized (GenericKeyedObjectPool.this) {
2178 _totalInternalProcessing--;
2179 }
2180 internalProcessingCount--;
2181 }
2182 }
2183
2184 /**
2185 * A simple "struct" encapsulating an object instance and a timestamp.
2186 *
2187 * Implements Comparable, objects are sorted from old to new.
2188 *
2189 * This is also used by {@link GenericObjectPool}.
2190 */
2191 static class ObjectTimestampPair implements Comparable {
2192
2193 /** Object instance */
2194 Object value;
2195
2196 /** timestamp */
2197 long tstamp;
2198
2199 /**
2200 * Create a new ObjectTimestampPair using the given object and the current system time.
2201 * @param val object instance
2202 */
2203 ObjectTimestampPair(Object val) {
2204 this(val, System.currentTimeMillis());
2205 }
2206
2207 /**
2208 * Create a new ObjectTimeStampPair using the given object and timestamp value.
2209 * @param val object instance
2210 * @param time long representation of timestamp
2211 */
2212 ObjectTimestampPair(Object val, long time) {
2213 value = val;
2214 tstamp = time;
2215 }
2216
2217 /**
2218 * Returns a string representation.
2219 *
2220 * @return String representing this ObjectTimestampPair
2221 */
2222 public String toString() {
2223 return value + ";" + tstamp;
2224 }
2225
2226 /**
2227 * Compares this to another object by casting the argument to an
2228 * ObjectTimestampPair.
2229 *
2230 * @param obj object to cmpare
2231 * @return result of comparison
2232 */
2233 public int compareTo(Object obj) {
2234 return compareTo((ObjectTimestampPair) obj);
2235 }
2236
2237 /**
2238 * Compares this to another ObjectTimestampPair, using the timestamp as basis for comparison.
2239 * Implementation is consistent with equals.
2240 *
2241 * @param other object to compare
2242 * @return result of comparison
2243 */
2244 public int compareTo(ObjectTimestampPair other) {
2245 final long tstampdiff = this.tstamp - other.tstamp;
2246 if (tstampdiff == 0) {
2247 // make sure the natural ordering is consistent with equals
2248 // see java.lang.Comparable Javadocs
2249 return System.identityHashCode(this) - System.identityHashCode(other);
2250 } else {
2251 // handle int overflow
2252 return (int)Math.min(Math.max(tstampdiff, Integer.MIN_VALUE), Integer.MAX_VALUE);
2253 }
2254 }
2255 }
2256
2257 /**
2258 * The idle object evictor {@link TimerTask}.
2259 * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis
2260 */
2261 private class Evictor extends TimerTask {
2262 /**
2263 * Run pool maintenance. Evict objects qualifying for eviction and then
2264 * invoke {@link GenericKeyedObjectPool#ensureMinIdle()}.
2265 */
2266 public void run() {
2267 //Evict from the pool
2268 try {
2269 evict();
2270 } catch(Exception e) {
2271 // ignored
2272 } catch(OutOfMemoryError oome) {
2273 // Log problem but give evictor thread a chance to continue in
2274 // case error is recoverable
2275 oome.printStackTrace(System.err);
2276 }
2277 //Re-create idle instances.
2278 try {
2279 ensureMinIdle();
2280 } catch (Exception e) {
2281 // ignored
2282 }
2283 }
2284 }
2285
2286 /**
2287 * A simple "struct" encapsulating the
2288 * configuration information for a <code>GenericKeyedObjectPool</code>.
2289 * @see GenericKeyedObjectPool#GenericKeyedObjectPool(KeyedPoolableObjectFactory,GenericKeyedObjectPool.Config)
2290 * @see GenericKeyedObjectPool#setConfig
2291 */
2292 public static class Config {
2293 /**
2294 * @see GenericKeyedObjectPool#setMaxIdle
2295 */
2296 public int maxIdle = GenericKeyedObjectPool.DEFAULT_MAX_IDLE;
2297 /**
2298 * @see GenericKeyedObjectPool#setMaxActive
2299 */
2300 public int maxActive = GenericKeyedObjectPool.DEFAULT_MAX_ACTIVE;
2301 /**
2302 * @see GenericKeyedObjectPool#setMaxTotal
2303 */
2304 public int maxTotal = GenericKeyedObjectPool.DEFAULT_MAX_TOTAL;
2305 /**
2306 * @see GenericKeyedObjectPool#setMinIdle
2307 */
2308 public int minIdle = GenericKeyedObjectPool.DEFAULT_MIN_IDLE;
2309 /**
2310 * @see GenericKeyedObjectPool#setMaxWait
2311 */
2312 public long maxWait = GenericKeyedObjectPool.DEFAULT_MAX_WAIT;
2313 /**
2314 * @see GenericKeyedObjectPool#setWhenExhaustedAction
2315 */
2316 public byte whenExhaustedAction = GenericKeyedObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
2317 /**
2318 * @see GenericKeyedObjectPool#setTestOnBorrow
2319 */
2320 public boolean testOnBorrow = GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW;
2321 /**
2322 * @see GenericKeyedObjectPool#setTestOnReturn
2323 */
2324 public boolean testOnReturn = GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN;
2325 /**
2326 * @see GenericKeyedObjectPool#setTestWhileIdle
2327 */
2328 public boolean testWhileIdle = GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE;
2329 /**
2330 * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis
2331 */
2332 public long timeBetweenEvictionRunsMillis = GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
2333 /**
2334 * @see GenericKeyedObjectPool#setNumTestsPerEvictionRun
2335 */
2336 public int numTestsPerEvictionRun = GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
2337 /**
2338 * @see GenericKeyedObjectPool#setMinEvictableIdleTimeMillis
2339 */
2340 public long minEvictableIdleTimeMillis = GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
2341 /**
2342 * @see GenericKeyedObjectPool#setLifo
2343 */
2344 public boolean lifo = GenericKeyedObjectPool.DEFAULT_LIFO;
2345 }
2346
2347 /**
2348 * Latch used to control allocation order of objects to threads to ensure
2349 * fairness. That is, for each key, objects are allocated to threads in the order
2350 * that threads request objects.
2351 *
2352 * @since 1.5
2353 */
2354 private static final class Latch {
2355
2356 /** key of associated pool */
2357 private final Object _key;
2358
2359 /** keyed pool associated with this latch */
2360 private ObjectQueue _pool;
2361
2362 /** holds an ObjectTimestampPair when this latch has been allocated an instance */
2363 private ObjectTimestampPair _pair;
2364
2365 /** indicates that this latch can create an instance */
2366 private boolean _mayCreate = false;
2367
2368 /**
2369 * Create a latch with the given key
2370 * @param key key of the pool associated with this latch
2371 */
2372 private Latch(Object key) {
2373 _key = key;
2374 }
2375
2376 /**
2377 * Retuns the key of the associated pool
2378 * @return associated pool key
2379 */
2380 private synchronized Object getkey() {
2381 return _key;
2382 }
2383
2384 /**
2385 * Returns the pool associated with this latch
2386 * @return pool
2387 */
2388 private synchronized ObjectQueue getPool() {
2389 return _pool;
2390 }
2391
2392 /**
2393 * Sets the pool associated with this latch
2394 * @param pool the pool
2395 */
2396 private synchronized void setPool(ObjectQueue pool) {
2397 _pool = pool;
2398 }
2399
2400 /**
2401 * Gets the ObjectTimestampPair allocated to this latch.
2402 * Returns null if this latch does not have an instance allocated to it.
2403 * @return the associated ObjectTimestampPair
2404 */
2405 private synchronized ObjectTimestampPair getPair() {
2406 return _pair;
2407 }
2408
2409 /**
2410 * Allocate an ObjectTimestampPair to this latch.
2411 * @param pair ObjectTimestampPair on this latch
2412 */
2413 private synchronized void setPair(ObjectTimestampPair pair) {
2414 _pair = pair;
2415 }
2416
2417 /**
2418 * Whether or not this latch can create an instance
2419 * @return true if this latch has an instance creation permit
2420 */
2421 private synchronized boolean mayCreate() {
2422 return _mayCreate;
2423 }
2424
2425 /**
2426 * Sets the mayCreate property
2427 *
2428 * @param mayCreate true means this latch can create an instance
2429 */
2430 private synchronized void setMayCreate(boolean mayCreate) {
2431 _mayCreate = mayCreate;
2432 }
2433
2434 /**
2435 * Reset the latch data. Used when an allocation fails and the latch
2436 * needs to be re-added to the queue.
2437 */
2438 private synchronized void reset() {
2439 _pair = null;
2440 _mayCreate = false;
2441 }
2442 }
2443
2444 //--- protected attributes ---------------------------------------
2445
2446 /**
2447 * The cap on the number of idle instances in the pool.
2448 * @see #setMaxIdle
2449 * @see #getMaxIdle
2450 */
2451 private int _maxIdle = DEFAULT_MAX_IDLE;
2452
2453 /**
2454 * The minimum no of idle objects to keep in the pool.
2455 * @see #setMinIdle
2456 * @see #getMinIdle
2457 */
2458 private int _minIdle = DEFAULT_MIN_IDLE;
2459
2460 /**
2461 * The cap on the number of active instances from the pool.
2462 * @see #setMaxActive
2463 * @see #getMaxActive
2464 */
2465 private int _maxActive = DEFAULT_MAX_ACTIVE;
2466
2467 /**
2468 * The cap on the total number of instances from the pool if non-positive.
2469 * @see #setMaxTotal
2470 * @see #getMaxTotal
2471 */
2472 private int _maxTotal = DEFAULT_MAX_TOTAL;
2473
2474 /**
2475 * The maximum amount of time (in millis) the
2476 * {@link #borrowObject} method should block before throwing
2477 * an exception when the pool is exhausted and the
2478 * {@link #getWhenExhaustedAction "when exhausted" action} is
2479 * {@link #WHEN_EXHAUSTED_BLOCK}.
2480 *
2481 * When less than or equal to 0, the {@link #borrowObject} method
2482 * may block indefinitely.
2483 *
2484 * @see #setMaxWait
2485 * @see #getMaxWait
2486 * @see #WHEN_EXHAUSTED_BLOCK
2487 * @see #setWhenExhaustedAction
2488 * @see #getWhenExhaustedAction
2489 */
2490 private long _maxWait = DEFAULT_MAX_WAIT;
2491
2492 /**
2493 * The action to take when the {@link #borrowObject} method
2494 * is invoked when the pool is exhausted (the maximum number
2495 * of "active" objects has been reached).
2496 *
2497 * @see #WHEN_EXHAUSTED_BLOCK
2498 * @see #WHEN_EXHAUSTED_FAIL
2499 * @see #WHEN_EXHAUSTED_GROW
2500 * @see #DEFAULT_WHEN_EXHAUSTED_ACTION
2501 * @see #setWhenExhaustedAction
2502 * @see #getWhenExhaustedAction
2503 */
2504 private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION;
2505
2506 /**
2507 * When <code>true</code>, objects will be
2508 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
2509 * before being returned by the {@link #borrowObject}
2510 * method. If the object fails to validate,
2511 * it will be dropped from the pool, and we will attempt
2512 * to borrow another.
2513 *
2514 * @see #setTestOnBorrow
2515 * @see #getTestOnBorrow
2516 */
2517 private volatile boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW;
2518
2519 /**
2520 * When <code>true</code>, objects will be
2521 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
2522 * before being returned to the pool within the
2523 * {@link #returnObject}.
2524 *
2525 * @see #getTestOnReturn
2526 * @see #setTestOnReturn
2527 */
2528 private volatile boolean _testOnReturn = DEFAULT_TEST_ON_RETURN;
2529
2530 /**
2531 * When <code>true</code>, objects will be
2532 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated}
2533 * by the idle object evictor (if any). If an object
2534 * fails to validate, it will be dropped from the pool.
2535 *
2536 * @see #setTestWhileIdle
2537 * @see #getTestWhileIdle
2538 * @see #getTimeBetweenEvictionRunsMillis
2539 * @see #setTimeBetweenEvictionRunsMillis
2540 */
2541 private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE;
2542
2543 /**
2544 * The number of milliseconds to sleep between runs of the
2545 * idle object evictor thread.
2546 * When non-positive, no idle object evictor thread will be
2547 * run.
2548 *
2549 * @see #setTimeBetweenEvictionRunsMillis
2550 * @see #getTimeBetweenEvictionRunsMillis
2551 */
2552 private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
2553
2554 /**
2555 * The number of objects to examine during each run of the
2556 * idle object evictor thread (if any).
2557 * <p>
2558 * When a negative value is supplied, <code>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</code>
2559 * tests will be run. I.e., when the value is <code>-n</code>, roughly one <code>n</code>th of the
2560 * idle objects will be tested per run.
2561 *
2562 * @see #setNumTestsPerEvictionRun
2563 * @see #getNumTestsPerEvictionRun
2564 * @see #getTimeBetweenEvictionRunsMillis
2565 * @see #setTimeBetweenEvictionRunsMillis
2566 */
2567 private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
2568
2569 /**
2570 * The minimum amount of time an object may sit idle in the pool
2571 * before it is eligible for eviction by the idle object evictor
2572 * (if any).
2573 * When non-positive, no objects will be evicted from the pool
2574 * due to idle time alone.
2575 *
2576 * @see #setMinEvictableIdleTimeMillis
2577 * @see #getMinEvictableIdleTimeMillis
2578 * @see #getTimeBetweenEvictionRunsMillis
2579 * @see #setTimeBetweenEvictionRunsMillis
2580 */
2581 private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
2582
2583 /** My hash of pools (ObjectQueue). */
2584 private Map _poolMap = null;
2585
2586 /** The total number of active instances. */
2587 private int _totalActive = 0;
2588
2589 /** The total number of idle instances. */
2590 private int _totalIdle = 0;
2591
2592 /**
2593 * The number of objects subject to some form of internal processing
2594 * (usually creation or destruction) that should be included in the total
2595 * number of objects but are neither active nor idle.
2596 */
2597 private int _totalInternalProcessing = 0;
2598
2599 /** My {@link KeyedPoolableObjectFactory}. */
2600 private KeyedPoolableObjectFactory _factory = null;
2601
2602 /**
2603 * My idle object eviction {@link TimerTask}, if any.
2604 */
2605 private Evictor _evictor = null;
2606
2607 /**
2608 * A cursorable list of my pools.
2609 * @see GenericKeyedObjectPool.Evictor#run
2610 */
2611 private CursorableLinkedList _poolList = null;
2612
2613 /** Eviction cursor (over instances within-key) */
2614 private CursorableLinkedList.Cursor _evictionCursor = null;
2615
2616 /** Eviction cursor (over keys) */
2617 private CursorableLinkedList.Cursor _evictionKeyCursor = null;
2618
2619 /** Whether or not the pools behave as LIFO queues (last in first out) */
2620 private boolean _lifo = DEFAULT_LIFO;
2621
2622 /**
2623 * Used to track the order in which threads call {@link #borrowObject()} so
2624 * that objects can be allocated in the order in which the threads requested
2625 * them.
2626 */
2627 private LinkedList _allocationQueue = new LinkedList();
2628
2629 }