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: 781288 $ $Date: 2009-06-03 03:52:20 -0400 (Wed, 03 Jun 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 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 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. 927 * 928 * @param numTestsPerEvictionRun number of objects to examine each eviction run. 929 * @see #getNumTestsPerEvictionRun 930 * @see #setTimeBetweenEvictionRunsMillis 931 */ 932 public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { 933 _numTestsPerEvictionRun = numTestsPerEvictionRun; 934 } 935 936 /** 937 * Returns the minimum amount of time an object may sit idle in the pool 938 * before it is eligible for eviction by the idle object evictor 939 * (if any). 940 * 941 * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction. 942 * @see #setMinEvictableIdleTimeMillis 943 * @see #setTimeBetweenEvictionRunsMillis 944 */ 945 public synchronized long getMinEvictableIdleTimeMillis() { 946 return _minEvictableIdleTimeMillis; 947 } 948 949 /** 950 * Sets the minimum amount of time an object may sit idle in the pool 951 * before it is eligible for eviction by the idle object evictor 952 * (if any). 953 * When non-positive, no objects will be evicted from the pool 954 * due to idle time alone. 955 * 956 * @param minEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before 957 * it is eligible for eviction. 958 * @see #getMinEvictableIdleTimeMillis 959 * @see #setTimeBetweenEvictionRunsMillis 960 */ 961 public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { 962 _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; 963 } 964 965 /** 966 * When <code>true</code>, objects will be 967 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} 968 * by the idle object evictor (if any). If an object 969 * fails to validate, it will be dropped from the pool. 970 * 971 * @return <code>true</code> when objects are validated when borrowed. 972 * @see #setTestWhileIdle 973 * @see #setTimeBetweenEvictionRunsMillis 974 */ 975 public synchronized boolean getTestWhileIdle() { 976 return _testWhileIdle; 977 } 978 979 /** 980 * When <code>true</code>, objects will be 981 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} 982 * by the idle object evictor (if any). If an object 983 * fails to validate, it will be dropped from the pool. 984 * 985 * @param testWhileIdle <code>true</code> so objects are validated when borrowed. 986 * @see #getTestWhileIdle 987 * @see #setTimeBetweenEvictionRunsMillis 988 */ 989 public synchronized void setTestWhileIdle(boolean testWhileIdle) { 990 _testWhileIdle = testWhileIdle; 991 } 992 993 /** 994 * Sets the configuration. 995 * @param conf the new configuration to use. 996 * @see GenericKeyedObjectPool.Config 997 */ 998 public synchronized void setConfig(GenericKeyedObjectPool.Config conf) { 999 setMaxIdle(conf.maxIdle); 1000 setMaxActive(conf.maxActive); 1001 setMaxTotal(conf.maxTotal); 1002 setMinIdle(conf.minIdle); 1003 setMaxWait(conf.maxWait); 1004 setWhenExhaustedAction(conf.whenExhaustedAction); 1005 setTestOnBorrow(conf.testOnBorrow); 1006 setTestOnReturn(conf.testOnReturn); 1007 setTestWhileIdle(conf.testWhileIdle); 1008 setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun); 1009 setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis); 1010 setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis); 1011 } 1012 1013 /** 1014 * Whether or not the idle object pools act as LIFO queues. True means 1015 * that borrowObject returns the most recently used ("last in") idle object 1016 * in a pool (if there are idle instances available). False means that 1017 * the pools behave as FIFO queues - objects are taken from idle object 1018 * pools in the order that they are returned. 1019 * 1020 * @return <code>true</code> if the pools are configured to act as LIFO queues 1021 * @since 1.4 1022 */ 1023 public synchronized boolean getLifo() { 1024 return _lifo; 1025 } 1026 1027 /** 1028 * Sets the LIFO property of the pools. True means that borrowObject returns 1029 * the most recently used ("last in") idle object in a pool (if there are 1030 * idle instances available). False means that the pools behave as FIFO 1031 * queues - objects are taken from idle object pools in the order that 1032 * they are returned. 1033 * 1034 * @param lifo the new value for the lifo property 1035 * @since 1.4 1036 */ 1037 public synchronized void setLifo(boolean lifo) { 1038 this._lifo = lifo; 1039 } 1040 1041 //-- ObjectPool methods ------------------------------------------ 1042 1043 /** 1044 * <p>Borrows an object from the keyed pool associated with the given key.</p> 1045 * 1046 * <p>If there is an idle instance available in the pool associated with the given key, then 1047 * either the most-recently returned (if {@link #getLifo() lifo} == true) or "oldest" (lifo == false) 1048 * instance sitting idle in the pool will be activated and returned. If activation fails, or 1049 * {@link #getTestOnBorrow() testOnBorrow} is set to true and validation fails, the instance is destroyed and the 1050 * next available instance is examined. This continues until either a valid instance is returned or there 1051 * are no more idle instances available.</p> 1052 * 1053 * <p>If there are no idle instances available in the pool associated with the given key, behavior 1054 * depends on the {@link #getMaxActive() maxActive}, {@link #getMaxTotal() maxTotal}, and (if applicable) 1055 * {@link #getWhenExhaustedAction() whenExhaustedAction} and {@link #getMaxWait() maxWait} properties. If the 1056 * number of instances checked out from the pool under the given key is less than <code>maxActive</code> and 1057 * the total number of instances in circulation (under all keys) is less than <code>maxTotal</code>, a new instance 1058 * is created, activated and (if applicable) validated and returned to the caller.</p> 1059 * 1060 * <p>If the associated keyed pool is exhausted (no available idle instances and no capacity to create new ones), 1061 * this method will either block ({@link #WHEN_EXHAUSTED_BLOCK}), throw a <code>NoSuchElementException</code> 1062 * ({@link #WHEN_EXHAUSTED_FAIL}), or grow ({@link #WHEN_EXHAUSTED_GROW} - ignoring maxActive, maxTotal properties). 1063 * The length of time that this method will block when <code>whenExhaustedAction == WHEN_EXHAUSTED_BLOCK</code> 1064 * is determined by the {@link #getMaxWait() maxWait} property.</p> 1065 * 1066 * <p>When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances 1067 * to become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads receive 1068 * available instances in request arrival order.</p> 1069 * 1070 * @param key pool key 1071 * @return object instance from the keyed pool 1072 * @throws NoSuchElementException if a keyed object instance cannot be returned. 1073 */ 1074 public Object borrowObject(Object key) throws Exception { 1075 long starttime = System.currentTimeMillis(); 1076 Latch latch = new Latch(key); 1077 byte whenExhaustedAction; 1078 long maxWait; 1079 synchronized (this) { 1080 // Get local copy of current config. Can't sync when used later as 1081 // it can result in a deadlock. Has the added advantage that config 1082 // is consistent for entire method execution 1083 whenExhaustedAction = _whenExhaustedAction; 1084 maxWait = _maxWait; 1085 1086 // Add this request to the queue 1087 _allocationQueue.add(latch); 1088 1089 // Work the allocation queue, allocating idle instances and 1090 // instance creation permits in request arrival order 1091 allocate(); 1092 } 1093 1094 for(;;) { 1095 synchronized (this) { 1096 assertOpen(); 1097 } 1098 // If no object was allocated 1099 if (null == latch.getPair()) { 1100 // Check to see if we were allowed to create one 1101 if (latch.mayCreate()) { 1102 // allow new object to be created 1103 } else { 1104 // the pool is exhausted 1105 switch(whenExhaustedAction) { 1106 case WHEN_EXHAUSTED_GROW: 1107 // allow new object to be created 1108 synchronized (this) { 1109 _allocationQueue.remove(latch); 1110 latch.getPool().incrementInternalProcessingCount(); 1111 } 1112 break; 1113 case WHEN_EXHAUSTED_FAIL: 1114 synchronized (this) { 1115 _allocationQueue.remove(latch); 1116 } 1117 throw new NoSuchElementException("Pool exhausted"); 1118 case WHEN_EXHAUSTED_BLOCK: 1119 try { 1120 synchronized (latch) { 1121 if (maxWait <= 0) { 1122 latch.wait(); 1123 } else { 1124 // this code may be executed again after a notify then continue cycle 1125 // so, need to calculate the amount of time to wait 1126 final long elapsed = (System.currentTimeMillis() - starttime); 1127 final long waitTime = maxWait - elapsed; 1128 if (waitTime > 0) 1129 { 1130 latch.wait(waitTime); 1131 } 1132 } 1133 } 1134 } catch(InterruptedException e) { 1135 Thread.currentThread().interrupt(); 1136 throw e; 1137 } 1138 if (maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) { 1139 throw new NoSuchElementException("Timeout waiting for idle object"); 1140 } else { 1141 continue; // keep looping 1142 } 1143 default: 1144 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + 1145 " not recognized."); 1146 } 1147 } 1148 } 1149 1150 boolean newlyCreated = false; 1151 if (null == latch.getPair()) { 1152 try { 1153 Object obj = _factory.makeObject(key); 1154 latch.setPair(new ObjectTimestampPair(obj)); 1155 newlyCreated = true; 1156 } finally { 1157 if (!newlyCreated) { 1158 // object cannot be created 1159 synchronized (this) { 1160 latch.getPool().decrementInternalProcessingCount(); 1161 // No need to reset latch - about to throw exception 1162 allocate(); 1163 } 1164 } 1165 } 1166 } 1167 1168 // activate & validate the object 1169 try { 1170 _factory.activateObject(key, latch.getPair().value); 1171 if (_testOnBorrow && !_factory.validateObject(key, latch.getPair().value)) { 1172 throw new Exception("ValidateObject failed"); 1173 } 1174 synchronized (this) { 1175 latch.getPool().decrementInternalProcessingCount(); 1176 latch.getPool().incrementActiveCount(); 1177 } 1178 return latch.getPair().value; 1179 } catch (Throwable e) { 1180 // object cannot be activated or is invalid 1181 try { 1182 _factory.destroyObject(key, latch.getPair().value); 1183 } catch (Throwable e2) { 1184 // cannot destroy broken object 1185 } 1186 synchronized (this) { 1187 latch.getPool().decrementInternalProcessingCount(); 1188 latch.reset(); 1189 _allocationQueue.add(0, latch); 1190 allocate(); 1191 } 1192 if (newlyCreated) { 1193 throw new NoSuchElementException( 1194 "Could not create a validated object, cause: " + 1195 e.getMessage()); 1196 } 1197 else { 1198 continue; // keep looping 1199 } 1200 } 1201 } 1202 } 1203 1204 /** 1205 * Allocate available instances to latches in the allocation queue. Then 1206 * set _mayCreate to true for as many additional latches remaining in queue 1207 * as _maxActive allows for each key. 1208 */ 1209 private void allocate() { 1210 boolean clearOldest = false; 1211 1212 synchronized (this) { 1213 if (isClosed()) return; 1214 1215 for (;;) { 1216 if (!_allocationQueue.isEmpty()) { 1217 // First use any objects in the pool to clear the queue 1218 Latch latch = (Latch) _allocationQueue.getFirst(); 1219 ObjectQueue pool = (ObjectQueue)(_poolMap.get(latch.getkey())); 1220 if (null == pool) { 1221 pool = new ObjectQueue(); 1222 _poolMap.put(latch.getkey(), pool); 1223 _poolList.add(latch.getkey()); 1224 } 1225 latch.setPool(pool); 1226 if (!pool.queue.isEmpty()) { 1227 _allocationQueue.removeFirst(); 1228 latch.setPair( 1229 (ObjectTimestampPair) pool.queue.removeFirst()); 1230 pool.incrementInternalProcessingCount(); 1231 _totalIdle--; 1232 synchronized (latch) { 1233 latch.notify(); 1234 } 1235 // Next item in queue 1236 continue; 1237 } 1238 1239 // If there is a totalMaxActive and we are at the limit then 1240 // we have to make room 1241 if ((_maxTotal > 0) && 1242 (_totalActive + _totalIdle + _totalInternalProcessing >= _maxTotal)) { 1243 clearOldest = true; 1244 break; 1245 } 1246 1247 // Second utilise any spare capacity to create new objects 1248 if ((_maxActive < 0 || pool.activeCount + pool.internalProcessingCount < _maxActive) && 1249 (_maxTotal < 0 || _totalActive + _totalIdle + _totalInternalProcessing < _maxTotal)) { 1250 // allow new object to be created 1251 _allocationQueue.removeFirst(); 1252 latch.setMayCreate(true); 1253 pool.incrementInternalProcessingCount(); 1254 synchronized (latch) { 1255 latch.notify(); 1256 } 1257 // Next item in queue 1258 continue; 1259 } 1260 } 1261 break; 1262 } 1263 } 1264 1265 if (clearOldest) { 1266 /* Clear oldest calls factory methods so it must be called from 1267 * outside the sync block. 1268 * It also needs to be outside the sync block as it calls 1269 * allocate(). If called inside the sync block, the call to 1270 * allocate() would be able to enter the sync block (since the 1271 * thread already has the lock) which may have unexpected, 1272 * unpleasant results. 1273 */ 1274 clearOldest(); 1275 } 1276 } 1277 1278 /** 1279 * Clears the pool, removing all pooled instances. 1280 */ 1281 public void clear() { 1282 Map toDestroy = new HashMap(); 1283 synchronized (this) { 1284 for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { 1285 Object key = it.next(); 1286 ObjectQueue pool = (ObjectQueue)_poolMap.get(key); 1287 // Copy objects to new list so pool.queue can be cleared inside 1288 // the sync 1289 List objects = new ArrayList(); 1290 objects.addAll(pool.queue); 1291 toDestroy.put(key, objects); 1292 it.remove(); 1293 _poolList.remove(key); 1294 _totalIdle = _totalIdle - pool.queue.size(); 1295 _totalInternalProcessing = 1296 _totalInternalProcessing + pool.queue.size(); 1297 pool.queue.clear(); 1298 } 1299 } 1300 destroy(toDestroy); 1301 } 1302 1303 /** 1304 * Clears oldest 15% of objects in pool. The method sorts the 1305 * objects into a TreeMap and then iterates the first 15% for removal. 1306 * 1307 * @since Pool 1.3 1308 */ 1309 public void clearOldest() { 1310 // Map of objects to destroy my key 1311 final Map toDestroy = new HashMap(); 1312 1313 // build sorted map of idle objects 1314 final Map map = new TreeMap(); 1315 synchronized (this) { 1316 for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { 1317 final Object key = keyiter.next(); 1318 final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue; 1319 for (Iterator it = list.iterator(); it.hasNext();) { 1320 // each item into the map uses the objectimestamppair object 1321 // as the key. It then gets sorted based on the timstamp field 1322 // each value in the map is the parent list it belongs in. 1323 map.put(it.next(), key); 1324 } 1325 } 1326 1327 // Now iterate created map and kill the first 15% plus one to account for zero 1328 Set setPairKeys = map.entrySet(); 1329 int itemsToRemove = ((int) (map.size() * 0.15)) + 1; 1330 1331 Iterator iter = setPairKeys.iterator(); 1332 while (iter.hasNext() && itemsToRemove > 0) { 1333 Map.Entry entry = (Map.Entry) iter.next(); 1334 // kind of backwards on naming. In the map, each key is the objecttimestamppair 1335 // because it has the ordering with the timestamp value. Each value that the 1336 // key references is the key of the list it belongs to. 1337 Object key = entry.getValue(); 1338 ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); 1339 final CursorableLinkedList list = 1340 ((ObjectQueue)(_poolMap.get(key))).queue; 1341 list.remove(pairTimeStamp); 1342 1343 if (toDestroy.containsKey(key)) { 1344 ((List)toDestroy.get(key)).add(pairTimeStamp); 1345 } else { 1346 List listForKey = new ArrayList(); 1347 listForKey.add(pairTimeStamp); 1348 toDestroy.put(key, listForKey); 1349 } 1350 // if that was the last object for that key, drop that pool 1351 if (list.isEmpty()) { 1352 _poolMap.remove(key); 1353 _poolList.remove(key); 1354 } 1355 _totalIdle--; 1356 _totalInternalProcessing++; 1357 itemsToRemove--; 1358 } 1359 1360 } 1361 destroy(toDestroy); 1362 } 1363 1364 /** 1365 * Clears the specified pool, removing all pooled instances corresponding to the given <code>key</code>. 1366 * 1367 * @param key the key to clear 1368 */ 1369 public void clear(Object key) { 1370 Map toDestroy = new HashMap(); 1371 1372 final ObjectQueue pool; 1373 synchronized (this) { 1374 pool = (ObjectQueue)(_poolMap.remove(key)); 1375 if (pool == null) { 1376 return; 1377 } else { 1378 _poolList.remove(key); 1379 } 1380 // Copy objects to new list so pool.queue can be cleared inside 1381 // the sync 1382 List objects = new ArrayList(); 1383 objects.addAll(pool.queue); 1384 toDestroy.put(key, objects); 1385 _totalIdle = _totalIdle - pool.queue.size(); 1386 _totalInternalProcessing = 1387 _totalInternalProcessing + pool.queue.size(); 1388 pool.queue.clear(); 1389 } 1390 destroy(toDestroy); 1391 } 1392 1393 /** 1394 * Assuming Map<Object,Collection<ObjectTimestampPair>>, destroy all 1395 * ObjectTimestampPair.value 1396 * 1397 * @param m Map containing keyed pools to clear 1398 */ 1399 private void destroy(Map m) { 1400 for (Iterator keys = m.keySet().iterator(); keys.hasNext();) { 1401 Object key = keys.next(); 1402 Collection c = (Collection) m.get(key); 1403 for (Iterator it = c.iterator(); it.hasNext();) { 1404 try { 1405 _factory.destroyObject( 1406 key,((ObjectTimestampPair)(it.next())).value); 1407 } catch(Exception e) { 1408 // ignore error, keep destroying the rest 1409 } finally { 1410 synchronized(this) { 1411 _totalInternalProcessing--; 1412 allocate(); 1413 } 1414 } 1415 } 1416 1417 } 1418 } 1419 1420 /** 1421 * Returns the total number of instances current borrowed from this pool but not yet returned. 1422 * 1423 * @return the total number of instances currently borrowed from this pool 1424 */ 1425 public synchronized int getNumActive() { 1426 return _totalActive; 1427 } 1428 1429 /** 1430 * Returns the total number of instances currently idle in this pool. 1431 * 1432 * @return the total number of instances currently idle in this pool 1433 */ 1434 public synchronized int getNumIdle() { 1435 return _totalIdle; 1436 } 1437 1438 /** 1439 * Returns the number of instances currently borrowed from but not yet returned 1440 * to the pool corresponding to the given <code>key</code>. 1441 * 1442 * @param key the key to query 1443 * @return the number of instances corresponding to the given <code>key</code> currently borrowed in this pool 1444 */ 1445 public synchronized int getNumActive(Object key) { 1446 final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); 1447 return pool != null ? pool.activeCount : 0; 1448 } 1449 1450 /** 1451 * Returns the number of instances corresponding to the given <code>key</code> currently idle in this pool. 1452 * 1453 * @param key the key to query 1454 * @return the number of instances corresponding to the given <code>key</code> currently idle in this pool 1455 */ 1456 public synchronized int getNumIdle(Object key) { 1457 final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); 1458 return pool != null ? pool.queue.size() : 0; 1459 } 1460 1461 /** 1462 * <p>Returns an object to a keyed pool.</p> 1463 * 1464 * <p>For the pool to function correctly, the object instance <strong>must</strong> have been borrowed 1465 * from the pool (under the same key) and not yet returned. Repeated <code>returnObject</code> calls on 1466 * the same object/key pair (with no <code>borrowObject</code> calls in between) will result in multiple 1467 * references to the object in the idle instance pool.</p> 1468 * 1469 * <p>If {@link #getMaxIdle() maxIdle} is set to a positive value and the number of idle instances under the given 1470 * key has reached this value, the returning instance is destroyed.</p> 1471 * 1472 * <p>If {@link #getTestOnReturn() testOnReturn} == true, the returning instance is validated before being returned 1473 * to the idle instance pool under the given key. In this case, if validation fails, the instance is destroyed.</p> 1474 * 1475 * @param key pool key 1476 * @param obj instance to return to the keyed pool 1477 * @throws Exception 1478 */ 1479 public void returnObject(Object key, Object obj) throws Exception { 1480 try { 1481 addObjectToPool(key, obj, true); 1482 } catch (Exception e) { 1483 if (_factory != null) { 1484 try { 1485 _factory.destroyObject(key, obj); 1486 } catch (Exception e2) { 1487 // swallowed 1488 } 1489 // TODO: Correctness here depends on control in addObjectToPool. 1490 // These two methods should be refactored, removing the 1491 // "behavior flag", decrementNumActive, from addObjectToPool. 1492 ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); 1493 if (pool != null) { 1494 synchronized(this) { 1495 pool.decrementActiveCount(); 1496 allocate(); 1497 } 1498 } 1499 } 1500 } 1501 } 1502 1503 /** 1504 * <p>Adds an object to the keyed pool.</p> 1505 * 1506 * <p>Validates the object if testOnReturn == true and passivates it before returning it to the pool. 1507 * if validation or passivation fails, or maxIdle is set and there is no room in the pool, the instance 1508 * is destroyed.</p> 1509 * 1510 * <p>Calls {@link #allocate()} on successful completion</p> 1511 * 1512 * @param key pool key 1513 * @param obj instance to add to the keyed pool 1514 * @param decrementNumActive whether or not to decrement the active count associated with the keyed pool 1515 * @throws Exception 1516 */ 1517 private void addObjectToPool(Object key, Object obj, 1518 boolean decrementNumActive) throws Exception { 1519 1520 // if we need to validate this object, do so 1521 boolean success = true; // whether or not this object passed validation 1522 if (_testOnReturn && !_factory.validateObject(key, obj)) { 1523 success = false; 1524 } else { 1525 _factory.passivateObject(key, obj); 1526 } 1527 1528 boolean shouldDestroy = !success; 1529 ObjectQueue pool; 1530 1531 // Add instance to pool if there is room and it has passed validation 1532 // (if testOnreturn is set) 1533 synchronized (this) { 1534 // grab the pool (list) of objects associated with the given key 1535 pool = (ObjectQueue) (_poolMap.get(key)); 1536 // if it doesn't exist, create it 1537 if (null == pool) { 1538 pool = new ObjectQueue(); 1539 _poolMap.put(key, pool); 1540 _poolList.add(key); 1541 } 1542 if (isClosed()) { 1543 shouldDestroy = true; 1544 } else { 1545 // if there's no space in the pool, flag the object for destruction 1546 // else if we passivated successfully, return it to the pool 1547 if (_maxIdle >= 0 && (pool.queue.size() >= _maxIdle)) { 1548 shouldDestroy = true; 1549 } else if (success) { 1550 // borrowObject always takes the first element from the queue, 1551 // so for LIFO, push on top, FIFO add to end 1552 if (_lifo) { 1553 pool.queue.addFirst(new ObjectTimestampPair(obj)); 1554 } else { 1555 pool.queue.addLast(new ObjectTimestampPair(obj)); 1556 } 1557 _totalIdle++; 1558 if (decrementNumActive) { 1559 pool.decrementActiveCount(); 1560 } 1561 allocate(); 1562 } 1563 } 1564 } 1565 1566 // Destroy the instance if necessary 1567 if (shouldDestroy) { 1568 try { 1569 _factory.destroyObject(key, obj); 1570 } catch(Exception e) { 1571 // ignored? 1572 } 1573 // Decrement active count *after* destroy if applicable 1574 if (decrementNumActive) { 1575 synchronized(this) { 1576 pool.decrementActiveCount(); 1577 allocate(); 1578 } 1579 } 1580 } 1581 } 1582 1583 /** 1584 * <p>Invalidates the object instance associated with the given key. Decrements the active count 1585 * associated with the given keyed pool and destroys the instance.</p> 1586 * 1587 * @param key pool key 1588 * @param obj instance to invalidate 1589 * @throws Exception if an exception occurs destroying the object 1590 */ 1591 public void invalidateObject(Object key, Object obj) throws Exception { 1592 try { 1593 _factory.destroyObject(key, obj); 1594 } finally { 1595 synchronized (this) { 1596 ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); 1597 if (null == pool) { 1598 pool = new ObjectQueue(); 1599 _poolMap.put(key, pool); 1600 _poolList.add(key); 1601 } 1602 pool.decrementActiveCount(); 1603 allocate(); // _totalActive has changed 1604 } 1605 } 1606 } 1607 1608 /** 1609 * Create an object using the {@link KeyedPoolableObjectFactory#makeObject factory}, 1610 * passivate it, and then place it in the idle object pool. 1611 * <code>addObject</code> is useful for "pre-loading" a pool with idle objects. 1612 * 1613 * @param key the key a new instance should be added to 1614 * @throws Exception when {@link KeyedPoolableObjectFactory#makeObject} fails. 1615 * @throws IllegalStateException when no {@link #setFactory factory} has been set or after {@link #close} has been 1616 * called on this pool. 1617 */ 1618 public void addObject(Object key) throws Exception { 1619 assertOpen(); 1620 if (_factory == null) { 1621 throw new IllegalStateException("Cannot add objects without a factory."); 1622 } 1623 Object obj = _factory.makeObject(key); 1624 try { 1625 assertOpen(); 1626 addObjectToPool(key, obj, false); 1627 } catch (IllegalStateException ex) { // Pool closed 1628 try { 1629 _factory.destroyObject(key, obj); 1630 } catch (Exception ex2) { 1631 // swallow 1632 } 1633 throw ex; 1634 } 1635 } 1636 1637 /** 1638 * Registers a key for pool control. 1639 * 1640 * If <code>populateImmediately</code> is <code>true</code> and 1641 * <code>minIdle > 0,</code> the pool under the given key will be 1642 * populated immediately with <code>minIdle</code> idle instances. 1643 * 1644 * @param key - The key to register for pool control. 1645 * @param populateImmediately - If this is <code>true</code>, the pool 1646 * will be populated immediately. 1647 * @since Pool 1.3 1648 */ 1649 public synchronized void preparePool(Object key, boolean populateImmediately) { 1650 ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); 1651 if (null == pool) { 1652 pool = new ObjectQueue(); 1653 _poolMap.put(key,pool); 1654 _poolList.add(key); 1655 } 1656 1657 if (populateImmediately) { 1658 try { 1659 // Create the pooled objects 1660 ensureMinIdle(key); 1661 } 1662 catch (Exception e) { 1663 //Do nothing 1664 } 1665 } 1666 } 1667 1668 /** 1669 * Closes the keyed object pool. Once the pool is closed, {@link #borrowObject(Object)} 1670 * will fail with IllegalStateException, but {@link #returnObject(Object, Object)} and 1671 * {@link #invalidateObject(Object, Object)} will continue to work. This method does not 1672 * {@link #clear()} the pool. The method is idempotent - that is, it is OK to call it on a closed 1673 * pool. 1674 * 1675 * @throws Exception 1676 */ 1677 public void close() throws Exception { 1678 super.close(); 1679 synchronized (this) { 1680 clear(); 1681 if (null != _evictionCursor) { 1682 _evictionCursor.close(); 1683 _evictionCursor = null; 1684 } 1685 if (null != _evictionKeyCursor) { 1686 _evictionKeyCursor.close(); 1687 _evictionKeyCursor = null; 1688 } 1689 startEvictor(-1L); 1690 } 1691 } 1692 1693 /** 1694 * <p>Sets the keyed poolable object factory associated with this pool.</p> 1695 * 1696 * <p>If this method is called when objects are checked out of any of the keyed pools, 1697 * an IllegalStateException is thrown. Calling this method also has the side effect of 1698 * destroying any idle instances in existing keyed pools.</p> 1699 * 1700 * @param factory KeyedPoolableObjectFactory to use when creating keyed object pool instances 1701 * @throws IllegalStateException if there are active (checked out) instances associated with this keyed object pool 1702 */ 1703 public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException { 1704 Map toDestroy = new HashMap(); 1705 synchronized (this) { 1706 assertOpen(); 1707 if (0 < getNumActive()) { 1708 throw new IllegalStateException("Objects are already active"); 1709 } else { 1710 for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { 1711 Object key = it.next(); 1712 ObjectQueue pool = (ObjectQueue)_poolMap.get(key); 1713 if (pool != null) { 1714 // Copy objects to new list so pool.queue can be cleared 1715 // inside the sync 1716 List objects = new ArrayList(); 1717 objects.addAll(pool.queue); 1718 toDestroy.put(key, objects); 1719 it.remove(); 1720 _poolList.remove(key); 1721 _totalIdle = _totalIdle - pool.queue.size(); 1722 _totalInternalProcessing = 1723 _totalInternalProcessing + pool.queue.size(); 1724 pool.queue.clear(); 1725 } 1726 } 1727 _factory = factory; 1728 } 1729 } 1730 destroy(toDestroy); 1731 } 1732 1733 /** 1734 * <p>Perform <code>numTests</code> idle object eviction tests, evicting 1735 * examined objects that meet the criteria for eviction. If 1736 * <code>testWhileIdle</code> is true, examined objects are validated 1737 * when visited (and removed if invalid); otherwise only objects that 1738 * have been idle for more than <code>minEvicableIdletimeMillis</code> 1739 * are removed.</p> 1740 * 1741 * <p>Successive activations of this method examine objects in keyed pools 1742 * in sequence, cycling through the keys and examining objects in 1743 * oldest-to-youngest order within the keyed pools.</p> 1744 * 1745 * @throws Exception when there is a problem evicting idle objects. 1746 */ 1747 public void evict() throws Exception { 1748 Object key = null; 1749 boolean testWhileIdle; 1750 long minEvictableIdleTimeMillis; 1751 1752 synchronized (this) { 1753 // Get local copy of current config. Can't sync when used later as 1754 // it can result in a deadlock. Has the added advantage that config 1755 // is consistent for entire method execution 1756 testWhileIdle = _testWhileIdle; 1757 minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis; 1758 1759 // Initialize key to last key value 1760 if (_evictionKeyCursor != null && 1761 _evictionKeyCursor._lastReturned != null) { 1762 key = _evictionKeyCursor._lastReturned.value(); 1763 } 1764 } 1765 1766 for (int i=0, m=getNumTests(); i<m; i++) { 1767 final ObjectTimestampPair pair; 1768 synchronized (this) { 1769 // make sure pool map is not empty; otherwise do nothing 1770 if (_poolMap == null || _poolMap.size() == 0) { 1771 continue; 1772 } 1773 1774 // if we don't have a key cursor, then create one 1775 if (null == _evictionKeyCursor) { 1776 resetEvictionKeyCursor(); 1777 key = null; 1778 } 1779 1780 // if we don't have an object cursor, create one 1781 if (null == _evictionCursor) { 1782 // if the _evictionKeyCursor has a next value, use this key 1783 if (_evictionKeyCursor.hasNext()) { 1784 key = _evictionKeyCursor.next(); 1785 resetEvictionObjectCursor(key); 1786 } else { 1787 // Reset the key cursor and try again 1788 resetEvictionKeyCursor(); 1789 if (_evictionKeyCursor != null) { 1790 if (_evictionKeyCursor.hasNext()) { 1791 key = _evictionKeyCursor.next(); 1792 resetEvictionObjectCursor(key); 1793 } 1794 } 1795 } 1796 } 1797 1798 if (_evictionCursor == null) { 1799 continue; // should never happen; do nothing 1800 } 1801 1802 // If eviction cursor is exhausted, try to move 1803 // to the next key and reset 1804 if ((_lifo && !_evictionCursor.hasPrevious()) || 1805 (!_lifo && !_evictionCursor.hasNext())) { 1806 if (_evictionKeyCursor != null) { 1807 if (_evictionKeyCursor.hasNext()) { 1808 key = _evictionKeyCursor.next(); 1809 resetEvictionObjectCursor(key); 1810 } else { // Need to reset Key cursor 1811 resetEvictionKeyCursor(); 1812 if (_evictionKeyCursor != null) { 1813 if (_evictionKeyCursor.hasNext()) { 1814 key = _evictionKeyCursor.next(); 1815 resetEvictionObjectCursor(key); 1816 } 1817 } 1818 } 1819 } 1820 } 1821 1822 if ((_lifo && !_evictionCursor.hasPrevious()) || 1823 (!_lifo && !_evictionCursor.hasNext())) { 1824 continue; // reset failed, do nothing 1825 } 1826 1827 // if LIFO and the _evictionCursor has a previous object, 1828 // or FIFO and _evictionCursor has a next object, test it 1829 pair = _lifo ? 1830 (ObjectTimestampPair) _evictionCursor.previous() : 1831 (ObjectTimestampPair) _evictionCursor.next(); 1832 _evictionCursor.remove(); 1833 _totalIdle--; 1834 _totalInternalProcessing++; 1835 } 1836 1837 boolean removeObject=false; 1838 if ((minEvictableIdleTimeMillis > 0) && 1839 (System.currentTimeMillis() - pair.tstamp > 1840 minEvictableIdleTimeMillis)) { 1841 removeObject=true; 1842 } 1843 if (testWhileIdle && removeObject == false) { 1844 boolean active = false; 1845 try { 1846 _factory.activateObject(key,pair.value); 1847 active = true; 1848 } catch(Exception e) { 1849 removeObject=true; 1850 } 1851 if (active) { 1852 if (!_factory.validateObject(key,pair.value)) { 1853 removeObject=true; 1854 } else { 1855 try { 1856 _factory.passivateObject(key,pair.value); 1857 } catch(Exception e) { 1858 removeObject=true; 1859 } 1860 } 1861 } 1862 } 1863 1864 if (removeObject) { 1865 try { 1866 _factory.destroyObject(key, pair.value); 1867 } catch(Exception e) { 1868 // ignored 1869 } finally { 1870 // Do not remove the key from the _poolList or _poolmap, 1871 // even if the list stored in the _poolMap for this key is 1872 // empty when minIdle > 0. 1873 // 1874 // Otherwise if it was the last object for that key, 1875 // drop that pool 1876 if (_minIdle == 0) { 1877 synchronized (this) { 1878 ObjectQueue objectQueue = 1879 (ObjectQueue)_poolMap.get(key); 1880 if (objectQueue != null && 1881 objectQueue.queue.isEmpty()) { 1882 _poolMap.remove(key); 1883 _poolList.remove(key); 1884 } 1885 } 1886 } 1887 } 1888 } 1889 synchronized (this) { 1890 if (!removeObject) { 1891 _evictionCursor.add(pair); 1892 _totalIdle++; 1893 if (_lifo) { 1894 // Skip over the element we just added back 1895 _evictionCursor.previous(); 1896 } 1897 } 1898 _totalInternalProcessing--; 1899 } 1900 } 1901 } 1902 1903 /** 1904 * Resets the eviction key cursor and closes any 1905 * associated eviction object cursor 1906 */ 1907 private void resetEvictionKeyCursor() { 1908 if (_evictionKeyCursor != null) { 1909 _evictionKeyCursor.close(); 1910 } 1911 _evictionKeyCursor = _poolList.cursor(); 1912 if (null != _evictionCursor) { 1913 _evictionCursor.close(); 1914 _evictionCursor = null; 1915 } 1916 } 1917 1918 /** 1919 * Resets the eviction object cursor for the given key 1920 * 1921 * @param key eviction key 1922 */ 1923 private void resetEvictionObjectCursor(Object key) { 1924 if (_evictionCursor != null) { 1925 _evictionCursor.close(); 1926 } 1927 if (_poolMap == null) { 1928 return; 1929 } 1930 ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); 1931 if (pool != null) { 1932 CursorableLinkedList queue = pool.queue; 1933 _evictionCursor = queue.cursor(_lifo ? queue.size() : 0); 1934 } 1935 } 1936 1937 /** 1938 * Iterates through all the known keys and creates any necessary objects to maintain 1939 * the minimum level of pooled objects. 1940 * @see #getMinIdle 1941 * @see #setMinIdle 1942 * @throws Exception If there was an error whilst creating the pooled objects. 1943 */ 1944 private void ensureMinIdle() throws Exception { 1945 //Check if should sustain the pool 1946 if (_minIdle > 0) { 1947 Object[] keysCopy; 1948 synchronized(this) { 1949 // Get the current set of keys 1950 keysCopy = _poolMap.keySet().toArray(); 1951 } 1952 1953 // Loop through all elements in _poolList 1954 // Find out the total number of max active and max idle for that class 1955 // If the number is less than the minIdle, do creation loop to boost numbers 1956 for (int i=0; i < keysCopy.length; i++) { 1957 //Get the next key to process 1958 ensureMinIdle(keysCopy[i]); 1959 } 1960 } 1961 } 1962 1963 /** 1964 * Re-creates any needed objects to maintain the minimum levels of 1965 * pooled objects for the specified key. 1966 * 1967 * This method uses {@link #calculateDefecit} to calculate the number 1968 * of objects to be created. {@link #calculateDefecit} can be overridden to 1969 * provide a different method of calculating the number of objects to be 1970 * created. 1971 * @param key The key to process 1972 * @throws Exception If there was an error whilst creating the pooled objects 1973 */ 1974 private void ensureMinIdle(Object key) throws Exception { 1975 // Calculate current pool objects 1976 ObjectQueue pool; 1977 synchronized(this) { 1978 pool = (ObjectQueue)(_poolMap.get(key)); 1979 } 1980 if (pool == null) { 1981 return; 1982 } 1983 1984 // this method isn't synchronized so the 1985 // calculateDeficit is done at the beginning 1986 // as a loop limit and a second time inside the loop 1987 // to stop when another thread already returned the 1988 // needed objects 1989 int objectDeficit = calculateDefecit(pool, false); 1990 1991 for (int i = 0; i < objectDeficit && calculateDefecit(pool, true) > 0; i++) { 1992 try { 1993 addObject(key); 1994 } finally { 1995 synchronized (this) { 1996 pool.decrementInternalProcessingCount(); 1997 allocate(); 1998 } 1999 } 2000 } 2001 } 2002 2003 //--- non-public methods ---------------------------------------- 2004 2005 /** 2006 * Start the eviction thread or service, or when 2007 * <code>delay</code> is non-positive, stop it 2008 * if it is already running. 2009 * 2010 * @param delay milliseconds between evictor runs. 2011 */ 2012 protected synchronized void startEvictor(long delay) { 2013 if (null != _evictor) { 2014 EvictionTimer.cancel(_evictor); 2015 _evictor = null; 2016 } 2017 if (delay > 0) { 2018 _evictor = new Evictor(); 2019 EvictionTimer.schedule(_evictor, delay, delay); 2020 } 2021 } 2022 2023 synchronized String debugInfo() { 2024 StringBuffer buf = new StringBuffer(); 2025 buf.append("Active: ").append(getNumActive()).append("\n"); 2026 buf.append("Idle: ").append(getNumIdle()).append("\n"); 2027 Iterator it = _poolMap.keySet().iterator(); 2028 while (it.hasNext()) { 2029 buf.append("\t").append(_poolMap.get(it.next())).append("\n"); 2030 } 2031 return buf.toString(); 2032 } 2033 2034 private synchronized int getNumTests() { 2035 if (_numTestsPerEvictionRun >= 0) { 2036 return _numTestsPerEvictionRun; 2037 } else { 2038 return(int)(Math.ceil(_totalIdle/Math.abs((double)_numTestsPerEvictionRun))); 2039 } 2040 } 2041 2042 /** 2043 * This returns the number of objects to create during the pool 2044 * sustain cycle. This will ensure that the minimum number of idle 2045 * instances is maintained without going past the maxActive value. 2046 * 2047 * @param pool the ObjectPool to calculate the deficit for 2048 * @param incrementInternal - Should the count of objects currently under 2049 * some form of internal processing be 2050 * incremented? 2051 * @return The number of objects to be created 2052 */ 2053 private synchronized int calculateDefecit(ObjectQueue pool, 2054 boolean incrementInternal) { 2055 int objectDefecit = 0; 2056 2057 //Calculate no of objects needed to be created, in order to have 2058 //the number of pooled objects < maxActive(); 2059 objectDefecit = getMinIdle() - pool.queue.size(); 2060 if (getMaxActive() > 0) { 2061 int growLimit = Math.max(0, getMaxActive() - pool.activeCount - pool.queue.size() - pool.internalProcessingCount); 2062 objectDefecit = Math.min(objectDefecit, growLimit); 2063 } 2064 2065 // Take the maxTotal limit into account 2066 if (getMaxTotal() > 0) { 2067 int growLimit = Math.max(0, getMaxTotal() - getNumActive() - getNumIdle() - _totalInternalProcessing); 2068 objectDefecit = Math.min(objectDefecit, growLimit); 2069 } 2070 2071 if (incrementInternal && objectDefecit > 0) { 2072 pool.incrementInternalProcessingCount(); 2073 } 2074 return objectDefecit; 2075 } 2076 2077 //--- inner classes ---------------------------------------------- 2078 2079 /** 2080 * A "struct" that keeps additional information about the actual queue of pooled objects. 2081 */ 2082 private class ObjectQueue { 2083 /** Number of instances checked out to clients from this queue */ 2084 private int activeCount = 0; 2085 2086 /** Idle instance queue */ 2087 private final CursorableLinkedList queue = new CursorableLinkedList(); 2088 2089 /** Number of instances in process of being created */ 2090 private int internalProcessingCount = 0; 2091 2092 /** Increment the active count for this queue */ 2093 void incrementActiveCount() { 2094 synchronized (GenericKeyedObjectPool.this) { 2095 _totalActive++; 2096 } 2097 activeCount++; 2098 } 2099 2100 /** Decrement the active count for this queue */ 2101 void decrementActiveCount() { 2102 synchronized (GenericKeyedObjectPool.this) { 2103 _totalActive--; 2104 } 2105 if (activeCount > 0) { 2106 activeCount--; 2107 } 2108 } 2109 2110 /** Record the fact that one more instance is queued for creation */ 2111 void incrementInternalProcessingCount() { 2112 synchronized (GenericKeyedObjectPool.this) { 2113 _totalInternalProcessing++; 2114 } 2115 internalProcessingCount++; 2116 } 2117 2118 /** Decrement the number of instances in process of being created */ 2119 void decrementInternalProcessingCount() { 2120 synchronized (GenericKeyedObjectPool.this) { 2121 _totalInternalProcessing--; 2122 } 2123 internalProcessingCount--; 2124 } 2125 } 2126 2127 /** 2128 * A simple "struct" encapsulating an object instance and a timestamp. 2129 * 2130 * Implements Comparable, objects are sorted from old to new. 2131 * 2132 * This is also used by {@link GenericObjectPool}. 2133 */ 2134 static class ObjectTimestampPair implements Comparable { 2135 2136 /** Object instance */ 2137 Object value; 2138 2139 /** timestamp */ 2140 long tstamp; 2141 2142 /** 2143 * Create a new ObjectTimestampPair using the given object and the current system time. 2144 * @param val object instance 2145 */ 2146 ObjectTimestampPair(Object val) { 2147 this(val, System.currentTimeMillis()); 2148 } 2149 2150 /** 2151 * Create a new ObjectTimeStampPair using the given object and timestamp value. 2152 * @param val object instance 2153 * @param time long representation of timestamp 2154 */ 2155 ObjectTimestampPair(Object val, long time) { 2156 value = val; 2157 tstamp = time; 2158 } 2159 2160 /** 2161 * Returns a string representation. 2162 * 2163 * @return String representing this ObjectTimestampPair 2164 */ 2165 public String toString() { 2166 return value + ";" + tstamp; 2167 } 2168 2169 /** 2170 * Compares this to another object by casting the argument to an 2171 * ObjectTimestampPair. 2172 * 2173 * @param obj object to cmpare 2174 * @return result of comparison 2175 */ 2176 public int compareTo(Object obj) { 2177 return compareTo((ObjectTimestampPair) obj); 2178 } 2179 2180 /** 2181 * Compares this to another ObjectTimestampPair, using the timestamp as basis for comparison. 2182 * Implementation is consistent with equals. 2183 * 2184 * @param other object to compare 2185 * @return result of comparison 2186 */ 2187 public int compareTo(ObjectTimestampPair other) { 2188 final long tstampdiff = this.tstamp - other.tstamp; 2189 if (tstampdiff == 0) { 2190 // make sure the natural ordering is consistent with equals 2191 // see java.lang.Comparable Javadocs 2192 return System.identityHashCode(this) - System.identityHashCode(other); 2193 } else { 2194 // handle int overflow 2195 return (int)Math.min(Math.max(tstampdiff, Integer.MIN_VALUE), Integer.MAX_VALUE); 2196 } 2197 } 2198 } 2199 2200 /** 2201 * The idle object evictor {@link TimerTask}. 2202 * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis 2203 */ 2204 private class Evictor extends TimerTask { 2205 public void run() { 2206 //Evict from the pool 2207 try { 2208 evict(); 2209 } catch(Exception e) { 2210 // ignored 2211 } catch(OutOfMemoryError oome) { 2212 // Log problem but give evictor thread a chance to continue in 2213 // case error is recoverable 2214 oome.printStackTrace(System.err); 2215 } 2216 //Re-create idle instances. 2217 try { 2218 ensureMinIdle(); 2219 } catch (Exception e) { 2220 // ignored 2221 } 2222 } 2223 } 2224 2225 /** 2226 * A simple "struct" encapsulating the 2227 * configuration information for a <code>GenericKeyedObjectPool</code>. 2228 * @see GenericKeyedObjectPool#GenericKeyedObjectPool(KeyedPoolableObjectFactory,GenericKeyedObjectPool.Config) 2229 * @see GenericKeyedObjectPool#setConfig 2230 */ 2231 public static class Config { 2232 /** 2233 * @see GenericKeyedObjectPool#setMaxIdle 2234 */ 2235 public int maxIdle = GenericKeyedObjectPool.DEFAULT_MAX_IDLE; 2236 /** 2237 * @see GenericKeyedObjectPool#setMaxActive 2238 */ 2239 public int maxActive = GenericKeyedObjectPool.DEFAULT_MAX_ACTIVE; 2240 /** 2241 * @see GenericKeyedObjectPool#setMaxTotal 2242 */ 2243 public int maxTotal = GenericKeyedObjectPool.DEFAULT_MAX_TOTAL; 2244 /** 2245 * @see GenericKeyedObjectPool#setMinIdle 2246 */ 2247 public int minIdle = GenericKeyedObjectPool.DEFAULT_MIN_IDLE; 2248 /** 2249 * @see GenericKeyedObjectPool#setMaxWait 2250 */ 2251 public long maxWait = GenericKeyedObjectPool.DEFAULT_MAX_WAIT; 2252 /** 2253 * @see GenericKeyedObjectPool#setWhenExhaustedAction 2254 */ 2255 public byte whenExhaustedAction = GenericKeyedObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION; 2256 /** 2257 * @see GenericKeyedObjectPool#setTestOnBorrow 2258 */ 2259 public boolean testOnBorrow = GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW; 2260 /** 2261 * @see GenericKeyedObjectPool#setTestOnReturn 2262 */ 2263 public boolean testOnReturn = GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN; 2264 /** 2265 * @see GenericKeyedObjectPool#setTestWhileIdle 2266 */ 2267 public boolean testWhileIdle = GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE; 2268 /** 2269 * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis 2270 */ 2271 public long timeBetweenEvictionRunsMillis = GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; 2272 /** 2273 * @see GenericKeyedObjectPool#setNumTestsPerEvictionRun 2274 */ 2275 public int numTestsPerEvictionRun = GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN; 2276 /** 2277 * @see GenericKeyedObjectPool#setMinEvictableIdleTimeMillis 2278 */ 2279 public long minEvictableIdleTimeMillis = GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; 2280 /** 2281 * @see GenericKeyedObjectPool#setLifo 2282 */ 2283 public boolean lifo = GenericKeyedObjectPool.DEFAULT_LIFO; 2284 } 2285 2286 /** 2287 * Latch used to control allocation order of objects to threads to ensure 2288 * fairness. That is, objects are allocated to threads in the order that threads 2289 * request objects. 2290 * 2291 * @since 1.5 2292 */ 2293 private static final class Latch { 2294 2295 /** key of associated pool */ 2296 private final Object _key; 2297 2298 /** keyed pool associated with this latch */ 2299 private ObjectQueue _pool; 2300 2301 /** holds an ObjectTimestampPair when this latch has been allocated an instance */ 2302 private ObjectTimestampPair _pair; 2303 2304 /** indicates that this latch can create an instance */ 2305 private boolean _mayCreate = false; 2306 2307 /** 2308 * Create a latch with the given key 2309 * @param key key of the pool associated with this latch 2310 */ 2311 private Latch(Object key) { 2312 _key = key; 2313 } 2314 2315 /** 2316 * Retuns the key of the associated pool 2317 * @return associated pool key 2318 */ 2319 private synchronized Object getkey() { 2320 return _key; 2321 } 2322 2323 /** 2324 * Returns the pool associated with this latch 2325 * @return pool 2326 */ 2327 private synchronized ObjectQueue getPool() { 2328 return _pool; 2329 } 2330 2331 /** 2332 * Sets the pool associated with this latch 2333 * @param pool the pool 2334 */ 2335 private synchronized void setPool(ObjectQueue pool) { 2336 _pool = pool; 2337 } 2338 2339 /** 2340 * Gets the ObjectTimestampPair allocated to this latch. 2341 * Returns null if this latch does not have an instance allocated to it. 2342 * @return the associated ObjectTimestampPair 2343 */ 2344 private synchronized ObjectTimestampPair getPair() { 2345 return _pair; 2346 } 2347 2348 /** 2349 * Allocate an ObjectTimestampPair to this latch. 2350 * @param pair ObjectTimestampPair on this latch 2351 */ 2352 private synchronized void setPair(ObjectTimestampPair pair) { 2353 _pair = pair; 2354 } 2355 2356 /** 2357 * Whether or not this latch can create an instance 2358 * @return true if this latch has an instance creation permit 2359 */ 2360 private synchronized boolean mayCreate() { 2361 return _mayCreate; 2362 } 2363 2364 /** 2365 * Sets the mayCreate property 2366 * 2367 * @param mayCreate true means this latch can create an instance 2368 */ 2369 private synchronized void setMayCreate(boolean mayCreate) { 2370 _mayCreate = mayCreate; 2371 } 2372 2373 /** 2374 * Reset the latch data. Used when an allocation fails and the latch 2375 * needs to be re-added to the queue. 2376 */ 2377 private synchronized void reset() { 2378 _pair = null; 2379 _mayCreate = false; 2380 } 2381 } 2382 2383 //--- protected attributes --------------------------------------- 2384 2385 /** 2386 * The cap on the number of idle instances in the pool. 2387 * @see #setMaxIdle 2388 * @see #getMaxIdle 2389 */ 2390 private int _maxIdle = DEFAULT_MAX_IDLE; 2391 2392 /** 2393 * The minimum no of idle objects to keep in the pool. 2394 * @see #setMinIdle 2395 * @see #getMinIdle 2396 */ 2397 private int _minIdle = DEFAULT_MIN_IDLE; 2398 2399 /** 2400 * The cap on the number of active instances from the pool. 2401 * @see #setMaxActive 2402 * @see #getMaxActive 2403 */ 2404 private int _maxActive = DEFAULT_MAX_ACTIVE; 2405 2406 /** 2407 * The cap on the total number of instances from the pool if non-positive. 2408 * @see #setMaxTotal 2409 * @see #getMaxTotal 2410 */ 2411 private int _maxTotal = DEFAULT_MAX_TOTAL; 2412 2413 /** 2414 * The maximum amount of time (in millis) the 2415 * {@link #borrowObject} method should block before throwing 2416 * an exception when the pool is exhausted and the 2417 * {@link #getWhenExhaustedAction "when exhausted" action} is 2418 * {@link #WHEN_EXHAUSTED_BLOCK}. 2419 * 2420 * When less than or equal to 0, the {@link #borrowObject} method 2421 * may block indefinitely. 2422 * 2423 * @see #setMaxWait 2424 * @see #getMaxWait 2425 * @see #WHEN_EXHAUSTED_BLOCK 2426 * @see #setWhenExhaustedAction 2427 * @see #getWhenExhaustedAction 2428 */ 2429 private long _maxWait = DEFAULT_MAX_WAIT; 2430 2431 /** 2432 * The action to take when the {@link #borrowObject} method 2433 * is invoked when the pool is exhausted (the maximum number 2434 * of "active" objects has been reached). 2435 * 2436 * @see #WHEN_EXHAUSTED_BLOCK 2437 * @see #WHEN_EXHAUSTED_FAIL 2438 * @see #WHEN_EXHAUSTED_GROW 2439 * @see #DEFAULT_WHEN_EXHAUSTED_ACTION 2440 * @see #setWhenExhaustedAction 2441 * @see #getWhenExhaustedAction 2442 */ 2443 private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION; 2444 2445 /** 2446 * When <code>true</code>, objects will be 2447 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} 2448 * before being returned by the {@link #borrowObject} 2449 * method. If the object fails to validate, 2450 * it will be dropped from the pool, and we will attempt 2451 * to borrow another. 2452 * 2453 * @see #setTestOnBorrow 2454 * @see #getTestOnBorrow 2455 */ 2456 private volatile boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW; 2457 2458 /** 2459 * When <code>true</code>, objects will be 2460 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} 2461 * before being returned to the pool within the 2462 * {@link #returnObject}. 2463 * 2464 * @see #getTestOnReturn 2465 * @see #setTestOnReturn 2466 */ 2467 private volatile boolean _testOnReturn = DEFAULT_TEST_ON_RETURN; 2468 2469 /** 2470 * When <code>true</code>, objects will be 2471 * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} 2472 * by the idle object evictor (if any). If an object 2473 * fails to validate, it will be dropped from the pool. 2474 * 2475 * @see #setTestWhileIdle 2476 * @see #getTestWhileIdle 2477 * @see #getTimeBetweenEvictionRunsMillis 2478 * @see #setTimeBetweenEvictionRunsMillis 2479 */ 2480 private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE; 2481 2482 /** 2483 * The number of milliseconds to sleep between runs of the 2484 * idle object evictor thread. 2485 * When non-positive, no idle object evictor thread will be 2486 * run. 2487 * 2488 * @see #setTimeBetweenEvictionRunsMillis 2489 * @see #getTimeBetweenEvictionRunsMillis 2490 */ 2491 private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; 2492 2493 /** 2494 * The number of objects to examine during each run of the 2495 * idle object evictor thread (if any). 2496 * <p> 2497 * When a negative value is supplied, <code>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</code> 2498 * tests will be run. I.e., when the value is <code>-n</code>, roughly one <code>n</code>th of the 2499 * idle objects will be tested per run. 2500 * 2501 * @see #setNumTestsPerEvictionRun 2502 * @see #getNumTestsPerEvictionRun 2503 * @see #getTimeBetweenEvictionRunsMillis 2504 * @see #setTimeBetweenEvictionRunsMillis 2505 */ 2506 private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN; 2507 2508 /** 2509 * The minimum amount of time an object may sit idle in the pool 2510 * before it is eligible for eviction by the idle object evictor 2511 * (if any). 2512 * When non-positive, no objects will be evicted from the pool 2513 * due to idle time alone. 2514 * 2515 * @see #setMinEvictableIdleTimeMillis 2516 * @see #getMinEvictableIdleTimeMillis 2517 * @see #getTimeBetweenEvictionRunsMillis 2518 * @see #setTimeBetweenEvictionRunsMillis 2519 */ 2520 private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; 2521 2522 /** My hash of pools (ObjectQueue). */ 2523 private Map _poolMap = null; 2524 2525 /** The total number of active instances. */ 2526 private int _totalActive = 0; 2527 2528 /** The total number of idle instances. */ 2529 private int _totalIdle = 0; 2530 2531 /** 2532 * The number of objects subject to some form of internal processing 2533 * (usually creation or destruction) that should be included in the total 2534 * number of objects but are neither active nor idle. 2535 */ 2536 private int _totalInternalProcessing = 0; 2537 2538 /** My {@link KeyedPoolableObjectFactory}. */ 2539 private KeyedPoolableObjectFactory _factory = null; 2540 2541 /** 2542 * My idle object eviction {@link TimerTask}, if any. 2543 */ 2544 private Evictor _evictor = null; 2545 2546 /** 2547 * A cursorable list of my pools. 2548 * @see GenericKeyedObjectPool.Evictor#run 2549 */ 2550 private CursorableLinkedList _poolList = null; 2551 2552 /** Eviction cursor (over instances within-key) */ 2553 private CursorableLinkedList.Cursor _evictionCursor = null; 2554 2555 /** Eviction cursor (over keys) */ 2556 private CursorableLinkedList.Cursor _evictionKeyCursor = null; 2557 2558 /** Whether or not the pools behave as LIFO queues (last in first out) */ 2559 private boolean _lifo = DEFAULT_LIFO; 2560 2561 /** 2562 * Used to track the order in which threads call {@link #borrowObject()} so 2563 * that objects can be allocated in the order in which the threads requested 2564 * them. 2565 */ 2566 private LinkedList _allocationQueue = new LinkedList(); 2567 2568 }