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.Iterator; 023 import java.util.LinkedList; 024 import java.util.List; 025 import java.util.NoSuchElementException; 026 import java.util.TimerTask; 027 028 import org.apache.commons.pool.BaseObjectPool; 029 import org.apache.commons.pool.ObjectPool; 030 import org.apache.commons.pool.PoolableObjectFactory; 031 import org.apache.commons.pool.impl.GenericKeyedObjectPool.ObjectTimestampPair; 032 033 /** 034 * A configurable {@link ObjectPool} implementation. 035 * <p> 036 * When coupled with the appropriate {@link PoolableObjectFactory}, 037 * <tt>GenericObjectPool</tt> provides robust pooling functionality for 038 * arbitrary objects. 039 * <p> 040 * A <tt>GenericObjectPool</tt> provides a number of configurable parameters: 041 * <ul> 042 * <li> 043 * {@link #setMaxActive <i>maxActive</i>} controls the maximum number of 044 * objects that can be allocated by the pool (checked out to clients, or 045 * idle awaiting checkout) at a given time. When non-positive, there is no 046 * limit to the number of objects that can be managed by the pool at one time. 047 * When {@link #setMaxActive <i>maxActive</i>} is reached, the pool is said 048 * to be exhausted. The default setting for this parameter is 8. 049 * </li> 050 * <li> 051 * {@link #setMaxIdle <i>maxIdle</i>} controls the maximum number of objects 052 * that can sit idle in the pool at any time. When negative, there is no 053 * limit to the number of objects that may be idle at one time. The default 054 * setting for this parameter is 8. 055 * </li> 056 * <li> 057 * {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} specifies the 058 * behavior of the {@link #borrowObject} method when the pool is exhausted: 059 * <ul> 060 * <li> 061 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is 062 * {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject} will throw 063 * a {@link NoSuchElementException} 064 * </li> 065 * <li> 066 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is 067 * {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject} will create a new 068 * object and return it (essentially making {@link #setMaxActive <i>maxActive</i>} 069 * meaningless.) 070 * </li> 071 * <li> 072 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} 073 * is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject} will block 074 * (invoke {@link Object#wait()}) until a new or idle object is available. 075 * If a positive {@link #setMaxWait <i>maxWait</i>} 076 * value is supplied, then {@link #borrowObject} will block for at 077 * most that many milliseconds, after which a {@link NoSuchElementException} 078 * will be thrown. If {@link #setMaxWait <i>maxWait</i>} is non-positive, 079 * the {@link #borrowObject} method will block indefinitely. 080 * </li> 081 * </ul> 082 * The default <code>whenExhaustedAction</code> setting is 083 * {@link #WHEN_EXHAUSTED_BLOCK} and the default <code>maxWait</code> 084 * setting is -1. By default, therefore, <code>borrowObject</code> will 085 * block indefinitely until an idle instance becomes available. 086 * </li> 087 * <li> 088 * When {@link #setTestOnBorrow <i>testOnBorrow</i>} is set, the pool will 089 * attempt to validate each object before it is returned from the 090 * {@link #borrowObject} method. (Using the provided factory's 091 * {@link PoolableObjectFactory#validateObject} method.) Objects that fail 092 * to validate will be dropped from the pool, and a different object will 093 * be borrowed. The default setting for this parameter is 094 * <code>false.</code> 095 * </li> 096 * <li> 097 * When {@link #setTestOnReturn <i>testOnReturn</i>} is set, the pool will 098 * attempt to validate each object before it is returned to the pool in the 099 * {@link #returnObject} method. (Using the provided factory's 100 * {@link PoolableObjectFactory#validateObject} 101 * method.) Objects that fail to validate will be dropped from the pool. 102 * The default setting for this parameter is <code>false.</code> 103 * </li> 104 * </ul> 105 * <p> 106 * Optionally, one may configure the pool to examine and possibly evict objects 107 * as they sit idle in the pool and to ensure that a minimum number of idle 108 * objects are available. This is performed by an "idle object eviction" 109 * thread, which runs asynchronously. Caution should be used when configuring 110 * this optional feature. Eviction runs require an exclusive synchronization 111 * lock on the pool, so if they run too frequently and / or incur excessive 112 * latency when creating, destroying or validating object instances, 113 * performance issues may result. The idle object eviction thread may be 114 * configured using the following attributes: 115 * <ul> 116 * <li> 117 * {@link #setTimeBetweenEvictionRunsMillis <i>timeBetweenEvictionRunsMillis</i>} 118 * indicates how long the eviction thread should sleep before "runs" of examining 119 * idle objects. When non-positive, no eviction thread will be launched. The 120 * default setting for this parameter is -1 (i.e., idle object eviction is 121 * disabled by default). 122 * </li> 123 * <li> 124 * {@link #setMinEvictableIdleTimeMillis <i>minEvictableIdleTimeMillis</i>} 125 * specifies the minimum amount of time that an object may sit idle in the pool 126 * before it is eligible for eviction due to idle time. When non-positive, no object 127 * will be dropped from the pool due to idle time alone. This setting has no 128 * effect unless <code>timeBetweenEvictionRunsMillis > 0.</code> The default 129 * setting for this parameter is 30 minutes. 130 * </li> 131 * <li> 132 * {@link #setTestWhileIdle <i>testWhileIdle</i>} indicates whether or not idle 133 * objects should be validated using the factory's 134 * {@link PoolableObjectFactory#validateObject} method. Objects that fail to 135 * validate will be dropped from the pool. This setting has no effect unless 136 * <code>timeBetweenEvictionRunsMillis > 0.</code> The default setting for 137 * this parameter is <code>false.</code> 138 * </li> 139 * <li> 140 * {@link #setSoftMinEvictableIdleTimeMillis <i>softMinEvictableIdleTimeMillis</i>} 141 * specifies the minimum amount of time an object may sit idle in the pool 142 * before it is eligible for eviction by the idle object evictor 143 * (if any), with the extra condition that at least "minIdle" object instances 144 * remain in the pool. When non-positive, no objects will be evicted from the pool 145 * due to idle time alone. This setting has no effect unless 146 * <code>timeBetweenEvictionRunsMillis > 0.</code> and it is superceded by 147 * {@link #setMinEvictableIdleTimeMillis <i>minEvictableIdleTimeMillis</i>} 148 * (that is, if <code>minEvictableIdleTimeMillis</code> is positive, then 149 * <code>softMinEvictableIdleTimeMillis</code> is ignored). The default setting for 150 * this parameter is -1 (disabled). 151 * </li> 152 * <li> 153 * {@link #setNumTestsPerEvictionRun <i>numTestsPerEvictionRun</i>} 154 * determines the number of objects examined in each run of the idle object 155 * evictor. This setting has no effect unless 156 * <code>timeBetweenEvictionRunsMillis > 0.</code> The default setting for 157 * this parameter is 3. 158 * </li> 159 * </ul> 160 * <p> 161 * <p> 162 * The pool can be configured to behave as a LIFO queue with respect to idle 163 * objects - always returning the most recently used object from the pool, 164 * or as a FIFO queue, where borrowObject always returns the oldest object 165 * in the idle object pool. 166 * <ul> 167 * <li> 168 * {@link #setLifo <i>lifo</i>} 169 * determines whether or not the pool returns idle objects in 170 * last-in-first-out order. The default setting for this parameter is 171 * <code>true.</code> 172 * </li> 173 * </ul> 174 * <p> 175 * GenericObjectPool is not usable without a {@link PoolableObjectFactory}. A 176 * non-<code>null</code> factory must be provided either as a constructor argument 177 * or via a call to {@link #setFactory} before the pool is used. 178 * <p> 179 * Implementation note: To prevent possible deadlocks, care has been taken to 180 * ensure that no call to a factory method will occur within a synchronization 181 * block. See POOL-125 and DBCP-44 for more information. 182 * 183 * @see GenericKeyedObjectPool 184 * @author Rodney Waldhoff 185 * @author Dirk Verbeeck 186 * @author Sandy McArthur 187 * @version $Revision: 778428 $ $Date: 2009-05-25 10:34:21 -0400 (Mon, 25 May 2009) $ 188 * @since Pool 1.0 189 */ 190 public class GenericObjectPool extends BaseObjectPool implements ObjectPool { 191 192 //--- public constants ------------------------------------------- 193 194 /** 195 * A "when exhausted action" type indicating that when the pool is 196 * exhausted (i.e., the maximum number of active objects has 197 * been reached), the {@link #borrowObject} 198 * method should fail, throwing a {@link NoSuchElementException}. 199 * @see #WHEN_EXHAUSTED_BLOCK 200 * @see #WHEN_EXHAUSTED_GROW 201 * @see #setWhenExhaustedAction 202 */ 203 public static final byte WHEN_EXHAUSTED_FAIL = 0; 204 205 /** 206 * A "when exhausted action" type indicating that when the pool 207 * is exhausted (i.e., the maximum number 208 * of active objects has been reached), the {@link #borrowObject} 209 * method should block until a new object is available, or the 210 * {@link #getMaxWait maximum wait time} has been reached. 211 * @see #WHEN_EXHAUSTED_FAIL 212 * @see #WHEN_EXHAUSTED_GROW 213 * @see #setMaxWait 214 * @see #getMaxWait 215 * @see #setWhenExhaustedAction 216 */ 217 public static final byte WHEN_EXHAUSTED_BLOCK = 1; 218 219 /** 220 * A "when exhausted action" type indicating that when the pool is 221 * exhausted (i.e., the maximum number 222 * of active objects has been reached), the {@link #borrowObject} 223 * method should simply create a new object anyway. 224 * @see #WHEN_EXHAUSTED_FAIL 225 * @see #WHEN_EXHAUSTED_GROW 226 * @see #setWhenExhaustedAction 227 */ 228 public static final byte WHEN_EXHAUSTED_GROW = 2; 229 230 /** 231 * The default cap on the number of "sleeping" instances in the pool. 232 * @see #getMaxIdle 233 * @see #setMaxIdle 234 */ 235 public static final int DEFAULT_MAX_IDLE = 8; 236 237 /** 238 * The default minimum number of "sleeping" instances in the pool 239 * before before the evictor thread (if active) spawns new objects. 240 * @see #getMinIdle 241 * @see #setMinIdle 242 */ 243 public static final int DEFAULT_MIN_IDLE = 0; 244 245 /** 246 * The default cap on the total number of active instances from the pool. 247 * @see #getMaxActive 248 */ 249 public static final int DEFAULT_MAX_ACTIVE = 8; 250 251 /** 252 * The default "when exhausted action" for the pool. 253 * @see #WHEN_EXHAUSTED_BLOCK 254 * @see #WHEN_EXHAUSTED_FAIL 255 * @see #WHEN_EXHAUSTED_GROW 256 * @see #setWhenExhaustedAction 257 */ 258 public static final byte DEFAULT_WHEN_EXHAUSTED_ACTION = WHEN_EXHAUSTED_BLOCK; 259 260 /** 261 * The default LIFO status. True means that borrowObject returns the 262 * most recently used ("last in") idle object in the pool (if there are 263 * idle instances available). False means that the pool behaves as a FIFO 264 * queue - objects are taken from the idle object pool in the order that 265 * they are returned to the pool. 266 * @see #setLifo 267 * @since 1.4 268 */ 269 public static final boolean DEFAULT_LIFO = true; 270 271 /** 272 * The default maximum amount of time (in milliseconds) the 273 * {@link #borrowObject} method should block before throwing 274 * an exception when the pool is exhausted and the 275 * {@link #getWhenExhaustedAction "when exhausted" action} is 276 * {@link #WHEN_EXHAUSTED_BLOCK}. 277 * @see #getMaxWait 278 * @see #setMaxWait 279 */ 280 public static final long DEFAULT_MAX_WAIT = -1L; 281 282 /** 283 * The default "test on borrow" value. 284 * @see #getTestOnBorrow 285 * @see #setTestOnBorrow 286 */ 287 public static final boolean DEFAULT_TEST_ON_BORROW = false; 288 289 /** 290 * The default "test on return" value. 291 * @see #getTestOnReturn 292 * @see #setTestOnReturn 293 */ 294 public static final boolean DEFAULT_TEST_ON_RETURN = false; 295 296 /** 297 * The default "test while idle" value. 298 * @see #getTestWhileIdle 299 * @see #setTestWhileIdle 300 * @see #getTimeBetweenEvictionRunsMillis 301 * @see #setTimeBetweenEvictionRunsMillis 302 */ 303 public static final boolean DEFAULT_TEST_WHILE_IDLE = false; 304 305 /** 306 * The default "time between eviction runs" value. 307 * @see #getTimeBetweenEvictionRunsMillis 308 * @see #setTimeBetweenEvictionRunsMillis 309 */ 310 public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L; 311 312 /** 313 * The default number of objects to examine per run in the 314 * idle object evictor. 315 * @see #getNumTestsPerEvictionRun 316 * @see #setNumTestsPerEvictionRun 317 * @see #getTimeBetweenEvictionRunsMillis 318 * @see #setTimeBetweenEvictionRunsMillis 319 */ 320 public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3; 321 322 /** 323 * The default value for {@link #getMinEvictableIdleTimeMillis}. 324 * @see #getMinEvictableIdleTimeMillis 325 * @see #setMinEvictableIdleTimeMillis 326 */ 327 public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L; 328 329 /** 330 * The default value for {@link #getSoftMinEvictableIdleTimeMillis}. 331 * @see #getSoftMinEvictableIdleTimeMillis 332 * @see #setSoftMinEvictableIdleTimeMillis 333 */ 334 public static final long DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = -1; 335 336 //--- constructors ----------------------------------------------- 337 338 /** 339 * Create a new <tt>GenericObjectPool</tt> with default properties. 340 */ 341 public GenericObjectPool() { 342 this(null, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, 343 DEFAULT_MIN_IDLE, DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, 344 DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); 345 } 346 347 /** 348 * Create a new <tt>GenericObjectPool</tt> using the specified factory. 349 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 350 */ 351 public GenericObjectPool(PoolableObjectFactory factory) { 352 this(factory, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, 353 DEFAULT_MIN_IDLE, DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, 354 DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); 355 } 356 357 /** 358 * Create a new <tt>GenericObjectPool</tt> using the specified values. 359 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 360 * @param config a non-<tt>null</tt> {@link GenericObjectPool.Config} describing my configuration 361 */ 362 public GenericObjectPool(PoolableObjectFactory factory, GenericObjectPool.Config config) { 363 this(factory, config.maxActive, config.whenExhaustedAction, config.maxWait, config.maxIdle, config.minIdle, 364 config.testOnBorrow, config.testOnReturn, config.timeBetweenEvictionRunsMillis, 365 config.numTestsPerEvictionRun, config.minEvictableIdleTimeMillis, config.testWhileIdle, 366 config.softMinEvictableIdleTimeMillis, config.lifo); 367 } 368 369 /** 370 * Create a new <tt>GenericObjectPool</tt> using the specified values. 371 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 372 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive}) 373 */ 374 public GenericObjectPool(PoolableObjectFactory factory, int maxActive) { 375 this(factory, maxActive, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, DEFAULT_MIN_IDLE, 376 DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, 377 DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); 378 } 379 380 /** 381 * Create a new <tt>GenericObjectPool</tt> using the specified values. 382 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 383 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive}) 384 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction}) 385 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and 386 * <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait}) 387 */ 388 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait) { 389 this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE, DEFAULT_MIN_IDLE, DEFAULT_TEST_ON_BORROW, 390 DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, 391 DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); 392 } 393 394 /** 395 * Create a new <tt>GenericObjectPool</tt> using the specified values. 396 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 397 * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) 398 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction}) 399 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and 400 * <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait}) 401 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method 402 * (see {@link #getTestOnBorrow}) 403 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method 404 * (see {@link #getTestOnReturn}) 405 */ 406 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, 407 boolean testOnBorrow, boolean testOnReturn) { 408 this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE, DEFAULT_MIN_IDLE, testOnBorrow, 409 testOnReturn, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, 410 DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); 411 } 412 413 /** 414 * Create a new <tt>GenericObjectPool</tt> using the specified values. 415 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 416 * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) 417 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction}) 418 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and 419 * <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait}) 420 * @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle}) 421 */ 422 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle) { 423 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_MIN_IDLE, DEFAULT_TEST_ON_BORROW, 424 DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, 425 DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); 426 } 427 428 /** 429 * Create a new <tt>GenericObjectPool</tt> using the specified values. 430 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 431 * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) 432 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction}) 433 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and 434 * <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait}) 435 * @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle}) 436 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method 437 * (see {@link #getTestOnBorrow}) 438 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method 439 * (see {@link #getTestOnReturn}) 440 */ 441 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, 442 int maxIdle, boolean testOnBorrow, boolean testOnReturn) { 443 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn, 444 DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, 445 DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); 446 } 447 448 /** 449 * Create a new <tt>GenericObjectPool</tt> using the specified values. 450 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 451 * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) 452 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) 453 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and 454 * <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) 455 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) 456 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} 457 * method (see {@link #setTestOnBorrow}) 458 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method 459 * (see {@link #setTestOnReturn}) 460 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects 461 * for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) 462 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread 463 * (if any) (see {@link #setNumTestsPerEvictionRun}) 464 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it 465 * is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) 466 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any 467 * (see {@link #setTestWhileIdle}) 468 */ 469 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, 470 int maxIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, 471 int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) { 472 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn, 473 timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle); 474 } 475 476 /** 477 * Create a new <tt>GenericObjectPool</tt> using the specified values. 478 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 479 * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) 480 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) 481 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and 482 * <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) 483 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) 484 * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle}) 485 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method 486 * (see {@link #setTestOnBorrow}) 487 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method 488 * (see {@link #setTestOnReturn}) 489 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects 490 * for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) 491 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread 492 * (if any) (see {@link #setNumTestsPerEvictionRun}) 493 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before 494 * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) 495 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any 496 * (see {@link #setTestWhileIdle}) 497 */ 498 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, 499 int maxIdle, int minIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, 500 int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) { 501 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, minIdle, testOnBorrow, testOnReturn, 502 timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle, 503 DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS); 504 } 505 506 /** 507 * Create a new <tt>GenericObjectPool</tt> using the specified values. 508 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 509 * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) 510 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) 511 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and 512 * <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) 513 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) 514 * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle}) 515 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} 516 * method (see {@link #setTestOnBorrow}) 517 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} 518 * method (see {@link #setTestOnReturn}) 519 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects 520 * for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) 521 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread 522 * (if any) (see {@link #setNumTestsPerEvictionRun}) 523 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before 524 * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) 525 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any 526 * (see {@link #setTestWhileIdle}) 527 * @param softMinEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is 528 * eligible for eviction with the extra condition that at least "minIdle" amount of object remain in the pool. 529 * (see {@link #setSoftMinEvictableIdleTimeMillis}) 530 * @since Pool 1.3 531 */ 532 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, 533 int maxIdle, int minIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, 534 int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle, 535 long softMinEvictableIdleTimeMillis) { 536 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, minIdle, testOnBorrow, testOnReturn, 537 timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle, 538 softMinEvictableIdleTimeMillis, DEFAULT_LIFO); 539 } 540 541 /** 542 * Create a new <tt>GenericObjectPool</tt> using the specified values. 543 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects 544 * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) 545 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) 546 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and 547 * <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) 548 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) 549 * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle}) 550 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} 551 * method (see {@link #setTestOnBorrow}) 552 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} 553 * method (see {@link #setTestOnReturn}) 554 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle 555 * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) 556 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction 557 * thread (if any) (see {@link #setNumTestsPerEvictionRun}) 558 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before 559 * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) 560 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any 561 * (see {@link #setTestWhileIdle}) 562 * @param softMinEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the 563 * pool before it is eligible for eviction with the extra condition that at least "minIdle" amount of object 564 * remain in the pool. (see {@link #setSoftMinEvictableIdleTimeMillis}) 565 * @param lifo whether or not objects are returned in last-in-first-out order from the idle object pool 566 * (see {@link #setLifo}) 567 * @since Pool 1.4 568 */ 569 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, 570 int maxIdle, int minIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, 571 int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle, 572 long softMinEvictableIdleTimeMillis, boolean lifo) { 573 _factory = factory; 574 _maxActive = maxActive; 575 _lifo = lifo; 576 switch(whenExhaustedAction) { 577 case WHEN_EXHAUSTED_BLOCK: 578 case WHEN_EXHAUSTED_FAIL: 579 case WHEN_EXHAUSTED_GROW: 580 _whenExhaustedAction = whenExhaustedAction; 581 break; 582 default: 583 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized."); 584 } 585 _maxWait = maxWait; 586 _maxIdle = maxIdle; 587 _minIdle = minIdle; 588 _testOnBorrow = testOnBorrow; 589 _testOnReturn = testOnReturn; 590 _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; 591 _numTestsPerEvictionRun = numTestsPerEvictionRun; 592 _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; 593 _softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis; 594 _testWhileIdle = testWhileIdle; 595 596 _pool = new CursorableLinkedList(); 597 startEvictor(_timeBetweenEvictionRunsMillis); 598 } 599 600 //--- public methods --------------------------------------------- 601 602 //--- configuration methods -------------------------------------- 603 604 /** 605 * Returns the maximum number of objects that can be allocated by the pool 606 * (checked out to clients, or idle awaiting checkout) at a given time. 607 * When non-positive, there is no limit to the number of objects that can 608 * be managed by the pool at one time. 609 * 610 * @return the cap on the total number of object instances managed by the pool. 611 * @see #setMaxActive 612 */ 613 public synchronized int getMaxActive() { 614 return _maxActive; 615 } 616 617 /** 618 * Sets the cap on the number of objects that can be allocated by the pool 619 * (checked out to clients, or idle awaiting checkout) at a given time. Use 620 * a negative value for no limit. 621 * 622 * @param maxActive The cap on the total number of object instances managed by the pool. 623 * Negative values mean that there is no limit to the number of objects allocated 624 * by the pool. 625 * @see #getMaxActive 626 */ 627 public synchronized void setMaxActive(int maxActive) { 628 _maxActive = maxActive; 629 allocate(); 630 } 631 632 /** 633 * Returns the action to take when the {@link #borrowObject} method 634 * is invoked when the pool is exhausted (the maximum number 635 * of "active" objects has been reached). 636 * 637 * @return one of {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW} 638 * @see #setWhenExhaustedAction 639 */ 640 public synchronized byte getWhenExhaustedAction() { 641 return _whenExhaustedAction; 642 } 643 644 /** 645 * Sets the action to take when the {@link #borrowObject} method 646 * is invoked when the pool is exhausted (the maximum number 647 * of "active" objects has been reached). 648 * 649 * @param whenExhaustedAction the action code, which must be one of 650 * {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL}, 651 * or {@link #WHEN_EXHAUSTED_GROW} 652 * @see #getWhenExhaustedAction 653 */ 654 public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) { 655 switch(whenExhaustedAction) { 656 case WHEN_EXHAUSTED_BLOCK: 657 case WHEN_EXHAUSTED_FAIL: 658 case WHEN_EXHAUSTED_GROW: 659 _whenExhaustedAction = whenExhaustedAction; 660 allocate(); 661 break; 662 default: 663 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized."); 664 } 665 } 666 667 668 /** 669 * Returns the maximum amount of time (in milliseconds) the 670 * {@link #borrowObject} method should block before throwing 671 * an exception when the pool is exhausted and the 672 * {@link #setWhenExhaustedAction "when exhausted" action} is 673 * {@link #WHEN_EXHAUSTED_BLOCK}. 674 * 675 * When less than or equal to 0, the {@link #borrowObject} method 676 * may block indefinitely. 677 * 678 * @return maximum number of milliseconds to block when borrowing an object. 679 * @see #setMaxWait 680 * @see #setWhenExhaustedAction 681 * @see #WHEN_EXHAUSTED_BLOCK 682 */ 683 public synchronized long getMaxWait() { 684 return _maxWait; 685 } 686 687 /** 688 * Sets the maximum amount of time (in milliseconds) the 689 * {@link #borrowObject} method should block before throwing 690 * an exception when the pool is exhausted and the 691 * {@link #setWhenExhaustedAction "when exhausted" action} is 692 * {@link #WHEN_EXHAUSTED_BLOCK}. 693 * 694 * When less than or equal to 0, the {@link #borrowObject} method 695 * may block indefinitely. 696 * 697 * @param maxWait maximum number of milliseconds to block when borrowing an object. 698 * @see #getMaxWait 699 * @see #setWhenExhaustedAction 700 * @see #WHEN_EXHAUSTED_BLOCK 701 */ 702 public synchronized void setMaxWait(long maxWait) { 703 _maxWait = maxWait; 704 allocate(); 705 } 706 707 /** 708 * Returns the cap on the number of "idle" instances in the pool. 709 * @return the cap on the number of "idle" instances in the pool. 710 * @see #setMaxIdle 711 */ 712 public synchronized int getMaxIdle() { 713 return _maxIdle; 714 } 715 716 /** 717 * Sets the cap on the number of "idle" instances in the pool. 718 * If maxIdle is set too low on heavily loaded systems it is possible you 719 * will see objects being destroyed and almost immediately new objects 720 * being created. This is a result of the active threads momentarily 721 * returning objects faster than they are requesting them them, causing the 722 * number of idle objects to rise above maxIdle. The best value for maxIdle 723 * for heavily loaded system will vary but the default is a good starting 724 * point. 725 * @param maxIdle The cap on the number of "idle" instances in the pool. 726 * Use a negative value to indicate an unlimited number of idle instances. 727 * @see #getMaxIdle 728 */ 729 public synchronized void setMaxIdle(int maxIdle) { 730 _maxIdle = maxIdle; 731 allocate(); 732 } 733 734 /** 735 * Sets the minimum number of objects allowed in the pool 736 * before the evictor thread (if active) spawns new objects. 737 * Note that no objects are created when 738 * <code>numActive + numIdle >= maxActive.</code> 739 * This setting has no effect if the idle object evictor is disabled 740 * (i.e. if <code>timeBetweenEvictionRunsMillis <= 0</code>). 741 * 742 * @param minIdle The minimum number of objects. 743 * @see #getMinIdle 744 * @see #getTimeBetweenEvictionRunsMillis() 745 */ 746 public synchronized void setMinIdle(int minIdle) { 747 _minIdle = minIdle; 748 allocate(); 749 } 750 751 /** 752 * Returns the minimum number of objects allowed in the pool 753 * before the evictor thread (if active) spawns new objects. 754 * (Note no objects are created when: numActive + numIdle >= maxActive) 755 * 756 * @return The minimum number of objects. 757 * @see #setMinIdle 758 */ 759 public synchronized int getMinIdle() { 760 return _minIdle; 761 } 762 763 /** 764 * When <tt>true</tt>, objects will be 765 * {@link PoolableObjectFactory#validateObject validated} 766 * before being returned by the {@link #borrowObject} 767 * method. If the object fails to validate, 768 * it will be dropped from the pool, and we will attempt 769 * to borrow another. 770 * 771 * @return <code>true</code> if objects are validated before being borrowed. 772 * @see #setTestOnBorrow 773 */ 774 public boolean getTestOnBorrow() { 775 return _testOnBorrow; 776 } 777 778 /** 779 * When <tt>true</tt>, objects will be 780 * {@link PoolableObjectFactory#validateObject validated} 781 * before being returned by the {@link #borrowObject} 782 * method. If the object fails to validate, 783 * it will be dropped from the pool, and we will attempt 784 * to borrow another. 785 * 786 * @param testOnBorrow <code>true</code> if objects should be validated before being borrowed. 787 * @see #getTestOnBorrow 788 */ 789 public void setTestOnBorrow(boolean testOnBorrow) { 790 _testOnBorrow = testOnBorrow; 791 } 792 793 /** 794 * When <tt>true</tt>, objects will be 795 * {@link PoolableObjectFactory#validateObject validated} 796 * before being returned to the pool within the 797 * {@link #returnObject}. 798 * 799 * @return <code>true</code> when objects will be validated after returned to {@link #returnObject}. 800 * @see #setTestOnReturn 801 */ 802 public boolean getTestOnReturn() { 803 return _testOnReturn; 804 } 805 806 /** 807 * When <tt>true</tt>, objects will be 808 * {@link PoolableObjectFactory#validateObject validated} 809 * before being returned to the pool within the 810 * {@link #returnObject}. 811 * 812 * @param testOnReturn <code>true</code> so objects will be validated after returned to {@link #returnObject}. 813 * @see #getTestOnReturn 814 */ 815 public void setTestOnReturn(boolean testOnReturn) { 816 _testOnReturn = testOnReturn; 817 } 818 819 /** 820 * Returns the number of milliseconds to sleep between runs of the 821 * idle object evictor thread. 822 * When non-positive, no idle object evictor thread will be 823 * run. 824 * 825 * @return number of milliseconds to sleep between evictor runs. 826 * @see #setTimeBetweenEvictionRunsMillis 827 */ 828 public synchronized long getTimeBetweenEvictionRunsMillis() { 829 return _timeBetweenEvictionRunsMillis; 830 } 831 832 /** 833 * Sets the number of milliseconds to sleep between runs of the 834 * idle object evictor thread. 835 * When non-positive, no idle object evictor thread will be 836 * run. 837 * 838 * @param timeBetweenEvictionRunsMillis number of milliseconds to sleep between evictor runs. 839 * @see #getTimeBetweenEvictionRunsMillis 840 */ 841 public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { 842 _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; 843 startEvictor(_timeBetweenEvictionRunsMillis); 844 } 845 846 /** 847 * Returns the max number of objects to examine during each run of the 848 * idle object evictor thread (if any). 849 * 850 * @return max number of objects to examine during each evictor run. 851 * @see #setNumTestsPerEvictionRun 852 * @see #setTimeBetweenEvictionRunsMillis 853 */ 854 public synchronized int getNumTestsPerEvictionRun() { 855 return _numTestsPerEvictionRun; 856 } 857 858 /** 859 * Sets the max number of objects to examine during each run of the 860 * idle object evictor thread (if any). 861 * <p> 862 * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt> 863 * tests will be run. That is, when the value is <i>-n</i>, roughly one <i>n</i>th of the 864 * idle objects will be tested per run. 865 * 866 * @param numTestsPerEvictionRun max number of objects to examine during each evictor run. 867 * @see #getNumTestsPerEvictionRun 868 * @see #setTimeBetweenEvictionRunsMillis 869 */ 870 public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { 871 _numTestsPerEvictionRun = numTestsPerEvictionRun; 872 } 873 874 /** 875 * Returns the minimum amount of time an object may sit idle in the pool 876 * before it is eligible for eviction by the idle object evictor 877 * (if any). 878 * 879 * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction. 880 * @see #setMinEvictableIdleTimeMillis 881 * @see #setTimeBetweenEvictionRunsMillis 882 */ 883 public synchronized long getMinEvictableIdleTimeMillis() { 884 return _minEvictableIdleTimeMillis; 885 } 886 887 /** 888 * Sets the minimum amount of time an object may sit idle in the pool 889 * before it is eligible for eviction by the idle object evictor 890 * (if any). 891 * When non-positive, no objects will be evicted from the pool 892 * due to idle time alone. 893 * @param minEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before 894 * it is eligible for eviction. 895 * @see #getMinEvictableIdleTimeMillis 896 * @see #setTimeBetweenEvictionRunsMillis 897 */ 898 public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { 899 _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; 900 } 901 902 /** 903 * Returns the minimum amount of time an object may sit idle in the pool 904 * before it is eligible for eviction by the idle object evictor 905 * (if any), with the extra condition that at least 906 * "minIdle" amount of object remain in the pool. 907 * 908 * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction. 909 * @since Pool 1.3 910 * @see #setSoftMinEvictableIdleTimeMillis 911 */ 912 public synchronized long getSoftMinEvictableIdleTimeMillis() { 913 return _softMinEvictableIdleTimeMillis; 914 } 915 916 /** 917 * Sets the minimum amount of time an object may sit idle in the pool 918 * before it is eligible for eviction by the idle object evictor 919 * (if any), with the extra condition that at least 920 * "minIdle" object instances remain in the pool. 921 * When non-positive, no objects will be evicted from the pool 922 * due to idle time alone. 923 * 924 * @param softMinEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before 925 * it is eligible for eviction. 926 * @since Pool 1.3 927 * @see #getSoftMinEvictableIdleTimeMillis 928 */ 929 public synchronized void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis) { 930 _softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis; 931 } 932 933 /** 934 * When <tt>true</tt>, objects will be 935 * {@link PoolableObjectFactory#validateObject validated} 936 * by the idle object evictor (if any). If an object 937 * fails to validate, it will be dropped from the pool. 938 * 939 * @return <code>true</code> when objects will be validated by the evictor. 940 * @see #setTestWhileIdle 941 * @see #setTimeBetweenEvictionRunsMillis 942 */ 943 public synchronized boolean getTestWhileIdle() { 944 return _testWhileIdle; 945 } 946 947 /** 948 * When <tt>true</tt>, objects will be 949 * {@link PoolableObjectFactory#validateObject validated} 950 * by the idle object evictor (if any). If an object 951 * fails to validate, it will be dropped from the pool. 952 * 953 * @param testWhileIdle <code>true</code> so objects will be validated by the evictor. 954 * @see #getTestWhileIdle 955 * @see #setTimeBetweenEvictionRunsMillis 956 */ 957 public synchronized void setTestWhileIdle(boolean testWhileIdle) { 958 _testWhileIdle = testWhileIdle; 959 } 960 961 /** 962 * Whether or not the idle object pool acts as a LIFO queue. True means 963 * that borrowObject returns the most recently used ("last in") idle object 964 * in the pool (if there are idle instances available). False means that 965 * the pool behaves as a FIFO queue - objects are taken from the idle object 966 * pool in the order that they are returned to the pool. 967 * 968 * @return <code>true</true> if the pool is configured to act as a LIFO queue 969 * @since 1.4 970 */ 971 public synchronized boolean getLifo() { 972 return _lifo; 973 } 974 975 /** 976 * Sets the LIFO property of the pool. True means that borrowObject returns 977 * the most recently used ("last in") idle object in the pool (if there are 978 * idle instances available). False means that the pool behaves as a FIFO 979 * queue - objects are taken from the idle object pool in the order that 980 * they are returned to the pool. 981 * 982 * @param lifo the new value for the LIFO property 983 * @since 1.4 984 */ 985 public synchronized void setLifo(boolean lifo) { 986 this._lifo = lifo; 987 } 988 989 /** 990 * Sets my configuration. 991 * 992 * @param conf configuration to use. 993 * @see GenericObjectPool.Config 994 */ 995 public synchronized void setConfig(GenericObjectPool.Config conf) { 996 setMaxIdle(conf.maxIdle); 997 setMinIdle(conf.minIdle); 998 setMaxActive(conf.maxActive); 999 setMaxWait(conf.maxWait); 1000 setWhenExhaustedAction(conf.whenExhaustedAction); 1001 setTestOnBorrow(conf.testOnBorrow); 1002 setTestOnReturn(conf.testOnReturn); 1003 setTestWhileIdle(conf.testWhileIdle); 1004 setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun); 1005 setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis); 1006 setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis); 1007 setSoftMinEvictableIdleTimeMillis(conf.softMinEvictableIdleTimeMillis); 1008 setLifo(conf.lifo); 1009 allocate(); 1010 } 1011 1012 //-- ObjectPool methods ------------------------------------------ 1013 1014 /** 1015 * <p>Borrows an object from the pool.</p> 1016 * 1017 * <p>If there is an idle instance available in the pool, then either the most-recently returned 1018 * (if {@link #getLifo() lifo} == true) or "oldest" (lifo == false) instance sitting idle in the pool 1019 * will be activated and returned. If activation fails, or {@link #getTestOnBorrow() testOnBorrow} is set 1020 * to true and validation fails, the instance is destroyed and the next available instance is examined. 1021 * This continues until either a valid instance is returned or there are no more idle instances available.</p> 1022 * 1023 * <p>If there are no idle instances available in the pool, behavior depends on the {@link #getMaxActive() maxActive} 1024 * and (if applicable) {@link #getWhenExhaustedAction() whenExhaustedAction} and {@link #getMaxWait() maxWait} 1025 * properties. If the number of instances checked out from the pool is less than <code>maxActive,</code> a new 1026 * instance is created, activated and (if applicable) validated and returned to the caller.</p> 1027 * 1028 * <p>If the pool is exhausted (no available idle instances and no capacity to create new ones), 1029 * this method will either block ({@link #WHEN_EXHAUSTED_BLOCK}), throw a <code>NoSuchElementException</code> 1030 * ({@link #WHEN_EXHAUSTED_FAIL}), or grow ({@link #WHEN_EXHAUSTED_GROW} - ignoring maxActive). 1031 * The length of time that this method will block when <code>whenExhaustedAction == WHEN_EXHAUSTED_BLOCK</code> 1032 * is determined by the {@link #getMaxWait() maxWait} property.</p> 1033 * 1034 * <p>When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances 1035 * to become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads receive 1036 * available instances in request arrival order.</p> 1037 * 1038 * @return object instance 1039 * @throws NoSuchElementException if an instance cannot be returned 1040 */ 1041 public Object borrowObject() throws Exception { 1042 long starttime = System.currentTimeMillis(); 1043 Latch latch = new Latch(); 1044 byte whenExhaustedAction; 1045 long maxWait; 1046 synchronized (this) { 1047 // Get local copy of current config. Can't sync when used later as 1048 // it can result in a deadlock. Has the added advantage that config 1049 // is consistent for entire method execution 1050 whenExhaustedAction = _whenExhaustedAction; 1051 maxWait = _maxWait; 1052 1053 // Add this request to the queue 1054 _allocationQueue.add(latch); 1055 1056 // Work the allocation queue, allocating idle instances and 1057 // instance creation permits in request arrival order 1058 allocate(); 1059 } 1060 1061 for(;;) { 1062 synchronized (this) { 1063 assertOpen(); 1064 } 1065 1066 // If no object was allocated from the pool above 1067 if(latch.getPair() == null) { 1068 // check if we were allowed to create one 1069 if(latch.mayCreate()) { 1070 // allow new object to be created 1071 } else { 1072 // the pool is exhausted 1073 switch(whenExhaustedAction) { 1074 case WHEN_EXHAUSTED_GROW: 1075 // allow new object to be created 1076 synchronized (this) { 1077 _allocationQueue.remove(latch); 1078 _numInternalProcessing++; 1079 } 1080 break; 1081 case WHEN_EXHAUSTED_FAIL: 1082 synchronized (this) { 1083 _allocationQueue.remove(latch); 1084 } 1085 throw new NoSuchElementException("Pool exhausted"); 1086 case WHEN_EXHAUSTED_BLOCK: 1087 try { 1088 synchronized (latch) { 1089 if(maxWait <= 0) { 1090 latch.wait(); 1091 } else { 1092 // this code may be executed again after a notify then continue cycle 1093 // so, need to calculate the amount of time to wait 1094 final long elapsed = (System.currentTimeMillis() - starttime); 1095 final long waitTime = maxWait - elapsed; 1096 if (waitTime > 0) 1097 { 1098 latch.wait(waitTime); 1099 } 1100 } 1101 } 1102 } catch(InterruptedException e) { 1103 Thread.currentThread().interrupt(); 1104 throw e; 1105 } 1106 if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) { 1107 throw new NoSuchElementException("Timeout waiting for idle object"); 1108 } else { 1109 continue; // keep looping 1110 } 1111 default: 1112 throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction + 1113 " not recognized."); 1114 } 1115 } 1116 } 1117 1118 boolean newlyCreated = false; 1119 if(null == latch.getPair()) { 1120 try { 1121 Object obj = _factory.makeObject(); 1122 latch.setPair(new ObjectTimestampPair(obj)); 1123 newlyCreated = true; 1124 } finally { 1125 if (!newlyCreated) { 1126 // object cannot be created 1127 synchronized (this) { 1128 _numInternalProcessing--; 1129 // No need to reset latch - about to throw exception 1130 allocate(); 1131 } 1132 } 1133 } 1134 } 1135 // activate & validate the object 1136 try { 1137 _factory.activateObject(latch.getPair().value); 1138 if(_testOnBorrow && 1139 !_factory.validateObject(latch.getPair().value)) { 1140 throw new Exception("ValidateObject failed"); 1141 } 1142 synchronized(this) { 1143 _numInternalProcessing--; 1144 _numActive++; 1145 } 1146 return latch.getPair().value; 1147 } 1148 catch (Throwable e) { 1149 // object cannot be activated or is invalid 1150 try { 1151 _factory.destroyObject(latch.getPair().value); 1152 } catch (Throwable e2) { 1153 // cannot destroy broken object 1154 } 1155 synchronized (this) { 1156 _numInternalProcessing--; 1157 latch.reset(); 1158 _allocationQueue.add(0, latch); 1159 allocate(); 1160 } 1161 if(newlyCreated) { 1162 throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); 1163 } 1164 else { 1165 continue; // keep looping 1166 } 1167 } 1168 } 1169 } 1170 1171 /** 1172 * Allocate available instances to latches in the allocation queue. Then 1173 * set _mayCreate to true for as many additional latches remaining in queue 1174 * as _maxActive allows. 1175 */ 1176 private synchronized void allocate() { 1177 if (isClosed()) return; 1178 1179 // First use any objects in the pool to clear the queue 1180 for (;;) { 1181 if (!_pool.isEmpty() && !_allocationQueue.isEmpty()) { 1182 Latch latch = (Latch) _allocationQueue.removeFirst(); 1183 latch.setPair((ObjectTimestampPair) _pool.removeFirst()); 1184 _numInternalProcessing++; 1185 synchronized (latch) { 1186 latch.notify(); 1187 } 1188 } else { 1189 break; 1190 } 1191 } 1192 1193 // Second utilise any spare capacity to create new objects 1194 for(;;) { 1195 if((!_allocationQueue.isEmpty()) && (_maxActive < 0 || (_numActive + _numInternalProcessing) < _maxActive)) { 1196 Latch latch = (Latch) _allocationQueue.removeFirst(); 1197 latch.setMayCreate(true); 1198 _numInternalProcessing++; 1199 synchronized (latch) { 1200 latch.notify(); 1201 } 1202 } else { 1203 break; 1204 } 1205 } 1206 } 1207 1208 /** 1209 * <p>Invalidates the given object instance. Decrements the active count 1210 * and destroys the instance.</p> 1211 * 1212 * @param obj instance to invalidate 1213 * @throws Exception if an exception occurs destroying the object 1214 */ 1215 public void invalidateObject(Object obj) throws Exception { 1216 try { 1217 if (_factory != null) { 1218 _factory.destroyObject(obj); 1219 } 1220 } finally { 1221 synchronized (this) { 1222 _numActive--; 1223 allocate(); 1224 } 1225 } 1226 } 1227 1228 /** 1229 * Clears any objects sitting idle in the pool. 1230 */ 1231 public void clear() { 1232 List toDestroy = new ArrayList(); 1233 1234 synchronized(this) { 1235 toDestroy.addAll(_pool); 1236 _numInternalProcessing = _numInternalProcessing + _pool._size; 1237 _pool.clear(); 1238 } 1239 destroy(toDestroy); 1240 } 1241 1242 /** 1243 * Private method to destroy all the objects in a collection. Assumes 1244 * objects in the collection are instances of ObjectTimestampPair 1245 * 1246 * @param c Collection of objects to destroy 1247 */ 1248 private void destroy(Collection c) { 1249 for (Iterator it = c.iterator(); it.hasNext();) { 1250 try { 1251 _factory.destroyObject(((ObjectTimestampPair)(it.next())).value); 1252 } catch(Exception e) { 1253 // ignore error, keep destroying the rest 1254 } finally { 1255 synchronized(this) { 1256 _numInternalProcessing--; 1257 allocate(); 1258 } 1259 } 1260 } 1261 } 1262 1263 /** 1264 * Return the number of instances currently borrowed from this pool. 1265 * 1266 * @return the number of instances currently borrowed from this pool 1267 */ 1268 public synchronized int getNumActive() { 1269 return _numActive; 1270 } 1271 1272 /** 1273 * Return the number of instances currently idle in this pool. 1274 * 1275 * @return the number of instances currently idle in this pool 1276 */ 1277 public synchronized int getNumIdle() { 1278 return _pool.size(); 1279 } 1280 1281 /** 1282 * <p>Returns an object instance to the pool.</p> 1283 * 1284 * <p>If {@link #getMaxIdle() maxIdle} is set to a positive value and the number of idle instances 1285 * has reached this value, the returning instance is destroyed.</p> 1286 * 1287 * <p>If {@link #getTestOnReturn() testOnReturn} == true, the returning instance is validated before being returned 1288 * to the idle instance pool. In this case, if validation fails, the instance is destroyed.</p> 1289 * 1290 * <p><strong>Note: </strong> There is no guard to prevent an object 1291 * being returned to the pool multiple times. Clients are expected to 1292 * discard references to returned objects and ensure that an object is not 1293 * returned to the pool multiple times in sequence (i.e., without being 1294 * borrowed again between returns). Violating this contract will result in 1295 * the same object appearing multiple times in the pool and pool counters 1296 * (numActive, numIdle) returning incorrect values.</p> 1297 * 1298 * @param obj instance to return to the pool 1299 */ 1300 public void returnObject(Object obj) throws Exception { 1301 try { 1302 addObjectToPool(obj, true); 1303 } catch (Exception e) { 1304 if (_factory != null) { 1305 try { 1306 _factory.destroyObject(obj); 1307 } catch (Exception e2) { 1308 // swallowed 1309 } 1310 // TODO: Correctness here depends on control in addObjectToPool. 1311 // These two methods should be refactored, removing the 1312 // "behavior flag", decrementNumActive, from addObjectToPool. 1313 synchronized(this) { 1314 _numActive--; 1315 allocate(); 1316 } 1317 } 1318 } 1319 } 1320 1321 /** 1322 * <p>Adds an object to the pool.</p> 1323 * 1324 * <p>Validates the object if testOnReturn == true and passivates it before returning it to the pool. 1325 * if validation or passivation fails, or maxIdle is set and there is no room in the pool, the instance 1326 * is destroyed.</p> 1327 * 1328 * <p>Calls {@link #allocate()} on successful completion</p> 1329 * 1330 * @param obj instance to add to the pool 1331 * @param decrementNumActive whether or not to decrement the active count 1332 * @throws Exception 1333 */ 1334 private void addObjectToPool(Object obj, boolean decrementNumActive) throws Exception { 1335 boolean success = true; 1336 if(_testOnReturn && !(_factory.validateObject(obj))) { 1337 success = false; 1338 } else { 1339 _factory.passivateObject(obj); 1340 } 1341 1342 boolean shouldDestroy = !success; 1343 1344 // Add instance to pool if there is room and it has passed validation 1345 // (if testOnreturn is set) 1346 synchronized (this) { 1347 if (isClosed()) { 1348 shouldDestroy = true; 1349 } else { 1350 if((_maxIdle >= 0) && (_pool.size() >= _maxIdle)) { 1351 shouldDestroy = true; 1352 } else if(success) { 1353 // borrowObject always takes the first element from the queue, 1354 // so for LIFO, push on top, FIFO add to end 1355 if (_lifo) { 1356 _pool.addFirst(new ObjectTimestampPair(obj)); 1357 } else { 1358 _pool.addLast(new ObjectTimestampPair(obj)); 1359 } 1360 if (decrementNumActive) { 1361 _numActive--; 1362 } 1363 allocate(); 1364 } 1365 } 1366 } 1367 1368 // Destroy the instance if necessary 1369 if(shouldDestroy) { 1370 try { 1371 _factory.destroyObject(obj); 1372 } catch(Exception e) { 1373 // ignored 1374 } 1375 // Decrement active count *after* destroy if applicable 1376 if (decrementNumActive) { 1377 synchronized(this) { 1378 _numActive--; 1379 allocate(); 1380 } 1381 } 1382 } 1383 1384 } 1385 1386 /** 1387 * Closes the pool. Once the pool is closed, {@link #borrowObject()} 1388 * will fail with IllegalStateException, but {@link #returnObject(Object)} and 1389 * {@link #invalidateObject(Object)} will continue to work. This method does not 1390 * {@link #clear()} the pool. The method is idempotent - that is, it is OK to call it on a closed 1391 * pool. 1392 * 1393 * @throws Exception 1394 */ 1395 public void close() throws Exception { 1396 super.close(); 1397 synchronized (this) { 1398 clear(); 1399 startEvictor(-1L); 1400 } 1401 } 1402 1403 /** 1404 * Sets the {@link PoolableObjectFactory factory} this pool uses 1405 * to create new instances. Trying to change 1406 * the <code>factory</code> while there are borrowed objects will 1407 * throw an {@link IllegalStateException}. 1408 * 1409 * @param factory the {@link PoolableObjectFactory} used to create new instances. 1410 * @throws IllegalStateException when the factory cannot be set at this time 1411 */ 1412 public void setFactory(PoolableObjectFactory factory) throws IllegalStateException { 1413 List toDestroy = new ArrayList(); 1414 synchronized (this) { 1415 assertOpen(); 1416 if(0 < getNumActive()) { 1417 throw new IllegalStateException("Objects are already active"); 1418 } else { 1419 toDestroy.addAll(_pool); 1420 _numInternalProcessing = _numInternalProcessing + _pool._size; 1421 _pool.clear(); 1422 } 1423 _factory = factory; 1424 } 1425 destroy(toDestroy); 1426 } 1427 1428 /** 1429 * <p>Perform <code>numTests</code> idle object eviction tests, evicting 1430 * examined objects that meet the criteria for eviction. If 1431 * <code>testWhileIdle</code> is true, examined objects are validated 1432 * when visited (and removed if invalid); otherwise only objects that 1433 * have been idle for more than <code>minEvicableIdletimeMillis</code> 1434 * are removed.</p> 1435 * 1436 * <p>Successive activations of this method examine objects in 1437 * in sequence, cycling through objects in oldest-to-youngest order.</p> 1438 * 1439 * @throws Exception if the pool is closed or eviction fails. 1440 */ 1441 public void evict() throws Exception { 1442 assertOpen(); 1443 synchronized (this) { 1444 if(_pool.isEmpty()) { 1445 return; 1446 } 1447 if (null == _evictionCursor) { 1448 _evictionCursor = (_pool.cursor(_lifo ? _pool.size() : 0)); 1449 } 1450 } 1451 1452 for (int i=0,m=getNumTests();i<m;i++) { 1453 final ObjectTimestampPair pair; 1454 synchronized (this) { 1455 if ((_lifo && !_evictionCursor.hasPrevious()) || 1456 !_lifo && !_evictionCursor.hasNext()) { 1457 _evictionCursor.close(); 1458 _evictionCursor = _pool.cursor(_lifo ? _pool.size() : 0); 1459 } 1460 1461 pair = _lifo ? 1462 (ObjectTimestampPair) _evictionCursor.previous() : 1463 (ObjectTimestampPair) _evictionCursor.next(); 1464 1465 _evictionCursor.remove(); 1466 _numInternalProcessing++; 1467 } 1468 1469 boolean removeObject = false; 1470 final long idleTimeMilis = System.currentTimeMillis() - pair.tstamp; 1471 if ((getMinEvictableIdleTimeMillis() > 0) && 1472 (idleTimeMilis > getMinEvictableIdleTimeMillis())) { 1473 removeObject = true; 1474 } else if ((getSoftMinEvictableIdleTimeMillis() > 0) && 1475 (idleTimeMilis > getSoftMinEvictableIdleTimeMillis()) && 1476 ((getNumIdle() + 1)> getMinIdle())) { // +1 accounts for object we are processing 1477 removeObject = true; 1478 } 1479 if(getTestWhileIdle() && !removeObject) { 1480 boolean active = false; 1481 try { 1482 _factory.activateObject(pair.value); 1483 active = true; 1484 } catch(Exception e) { 1485 removeObject=true; 1486 } 1487 if(active) { 1488 if(!_factory.validateObject(pair.value)) { 1489 removeObject=true; 1490 } else { 1491 try { 1492 _factory.passivateObject(pair.value); 1493 } catch(Exception e) { 1494 removeObject=true; 1495 } 1496 } 1497 } 1498 } 1499 1500 if (removeObject) { 1501 try { 1502 _factory.destroyObject(pair.value); 1503 } catch(Exception e) { 1504 // ignored 1505 } 1506 } 1507 synchronized (this) { 1508 if(!removeObject) { 1509 _evictionCursor.add(pair); 1510 if (_lifo) { 1511 // Skip over the element we just added back 1512 _evictionCursor.previous(); 1513 } 1514 } 1515 _numInternalProcessing--; 1516 } 1517 } 1518 } 1519 1520 /** 1521 * Check to see if we are below our minimum number of objects 1522 * if so enough to bring us back to our minimum. 1523 * 1524 * @throws Exception when {@link #addObject()} fails. 1525 */ 1526 private void ensureMinIdle() throws Exception { 1527 // this method isn't synchronized so the 1528 // calculateDeficit is done at the beginning 1529 // as a loop limit and a second time inside the loop 1530 // to stop when another thread already returned the 1531 // needed objects 1532 int objectDeficit = calculateDeficit(false); 1533 for ( int j = 0 ; j < objectDeficit && calculateDeficit(true) > 0 ; j++ ) { 1534 try { 1535 addObject(); 1536 } finally { 1537 synchronized (this) { 1538 _numInternalProcessing--; 1539 allocate(); 1540 } 1541 } 1542 } 1543 } 1544 1545 /** 1546 * This returns the number of objects to create during the pool 1547 * sustain cycle. This will ensure that the minimum number of idle 1548 * instances is maintained without going past the maxActive value. 1549 * 1550 * @param incrementInternal - Should the count of objects currently under 1551 * some form of internal processing be 1552 * incremented? 1553 * @return The number of objects to be created 1554 */ 1555 private synchronized int calculateDeficit(boolean incrementInternal) { 1556 int objectDeficit = getMinIdle() - getNumIdle(); 1557 if (_maxActive > 0) { 1558 int growLimit = Math.max(0, 1559 getMaxActive() - getNumActive() - getNumIdle() - _numInternalProcessing); 1560 objectDeficit = Math.min(objectDeficit, growLimit); 1561 } 1562 if (incrementInternal && objectDeficit >0) { 1563 _numInternalProcessing++; 1564 } 1565 return objectDeficit; 1566 } 1567 1568 /** 1569 * Create an object, and place it into the pool. 1570 * addObject() is useful for "pre-loading" a pool with idle objects. 1571 */ 1572 public void addObject() throws Exception { 1573 assertOpen(); 1574 if (_factory == null) { 1575 throw new IllegalStateException("Cannot add objects without a factory."); 1576 } 1577 Object obj = _factory.makeObject(); 1578 try { 1579 assertOpen(); 1580 addObjectToPool(obj, false); 1581 } catch (IllegalStateException ex) { // Pool closed 1582 try { 1583 _factory.destroyObject(obj); 1584 } catch (Exception ex2) { 1585 // swallow 1586 } 1587 throw ex; 1588 } 1589 } 1590 1591 //--- non-public methods ---------------------------------------- 1592 1593 /** 1594 * Start the eviction thread or service, or when 1595 * <i>delay</i> is non-positive, stop it 1596 * if it is already running. 1597 * 1598 * @param delay milliseconds between evictor runs. 1599 */ 1600 protected synchronized void startEvictor(long delay) { 1601 if(null != _evictor) { 1602 EvictionTimer.cancel(_evictor); 1603 _evictor = null; 1604 } 1605 if(delay > 0) { 1606 _evictor = new Evictor(); 1607 EvictionTimer.schedule(_evictor, delay, delay); 1608 } 1609 } 1610 1611 synchronized String debugInfo() { 1612 StringBuffer buf = new StringBuffer(); 1613 buf.append("Active: ").append(getNumActive()).append("\n"); 1614 buf.append("Idle: ").append(getNumIdle()).append("\n"); 1615 buf.append("Idle Objects:\n"); 1616 Iterator it = _pool.iterator(); 1617 long time = System.currentTimeMillis(); 1618 while(it.hasNext()) { 1619 ObjectTimestampPair pair = (ObjectTimestampPair)(it.next()); 1620 buf.append("\t").append(pair.value).append("\t").append(time - pair.tstamp).append("\n"); 1621 } 1622 return buf.toString(); 1623 } 1624 1625 private int getNumTests() { 1626 if(_numTestsPerEvictionRun >= 0) { 1627 return Math.min(_numTestsPerEvictionRun, _pool.size()); 1628 } else { 1629 return(int)(Math.ceil(_pool.size()/Math.abs((double)_numTestsPerEvictionRun))); 1630 } 1631 } 1632 1633 //--- inner classes ---------------------------------------------- 1634 1635 /** 1636 * The idle object evictor {@link TimerTask}. 1637 * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis 1638 */ 1639 private class Evictor extends TimerTask { 1640 public void run() { 1641 try { 1642 evict(); 1643 } catch(Exception e) { 1644 // ignored 1645 } catch(OutOfMemoryError oome) { 1646 // Log problem but give evictor thread a chance to continue in 1647 // case error is recoverable 1648 oome.printStackTrace(System.err); 1649 } 1650 try { 1651 ensureMinIdle(); 1652 } catch(Exception e) { 1653 // ignored 1654 } 1655 } 1656 } 1657 1658 /** 1659 * A simple "struct" encapsulating the 1660 * configuration information for a {@link GenericObjectPool}. 1661 * @see GenericObjectPool#GenericObjectPool(org.apache.commons.pool.PoolableObjectFactory, 1662 * org.apache.commons.pool.impl.GenericObjectPool.Config) 1663 * @see GenericObjectPool#setConfig 1664 */ 1665 public static class Config { 1666 /** 1667 * @see GenericObjectPool#setMaxIdle 1668 */ 1669 public int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE; 1670 /** 1671 * @see GenericObjectPool#setMinIdle 1672 */ 1673 public int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE; 1674 /** 1675 * @see GenericObjectPool#setMaxActive 1676 */ 1677 public int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE; 1678 /** 1679 * @see GenericObjectPool#setMaxWait 1680 */ 1681 public long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT; 1682 /** 1683 * @see GenericObjectPool#setWhenExhaustedAction 1684 */ 1685 public byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION; 1686 /** 1687 * @see GenericObjectPool#setTestOnBorrow 1688 */ 1689 public boolean testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW; 1690 /** 1691 * @see GenericObjectPool#setTestOnReturn 1692 */ 1693 public boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN; 1694 /** 1695 * @see GenericObjectPool#setTestWhileIdle 1696 */ 1697 public boolean testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE; 1698 /** 1699 * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis 1700 */ 1701 public long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; 1702 /** 1703 * @see GenericObjectPool#setNumTestsPerEvictionRun 1704 */ 1705 public int numTestsPerEvictionRun = GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN; 1706 /** 1707 * @see GenericObjectPool#setMinEvictableIdleTimeMillis 1708 */ 1709 public long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; 1710 /** 1711 * @see GenericObjectPool#setSoftMinEvictableIdleTimeMillis 1712 */ 1713 public long softMinEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS; 1714 /** 1715 * @see GenericObjectPool#setLifo 1716 */ 1717 public boolean lifo = GenericObjectPool.DEFAULT_LIFO; 1718 1719 } 1720 1721 /** 1722 * Latch used to control allocation order of objects to threads to ensure 1723 * fairness. That is, objects are allocated to threads in the order that 1724 * threads request objects. 1725 */ 1726 private static final class Latch { 1727 1728 /** object timestamp pair allocated to this latch */ 1729 private ObjectTimestampPair _pair; 1730 1731 /** Wheter or not this latch may create an object instance */ 1732 private boolean _mayCreate = false; 1733 1734 /** 1735 * Returns ObjectTimestampPair allocated to this latch 1736 * @return ObjectTimestampPair allocated to this latch 1737 */ 1738 private synchronized ObjectTimestampPair getPair() { 1739 return _pair; 1740 } 1741 1742 /** 1743 * Sets ObjectTimestampPair on this latch 1744 * @param pair ObjectTimestampPair allocated to this latch 1745 */ 1746 private synchronized void setPair(ObjectTimestampPair pair) { 1747 _pair = pair; 1748 } 1749 1750 /** 1751 * Whether or not this latch may create an object instance 1752 * @return true if this latch has an instance creation permit 1753 */ 1754 private synchronized boolean mayCreate() { 1755 return _mayCreate; 1756 } 1757 1758 /** 1759 * Sets the mayCreate property 1760 * @param mayCreate new value for mayCreate 1761 */ 1762 private synchronized void setMayCreate(boolean mayCreate) { 1763 _mayCreate = mayCreate; 1764 } 1765 1766 /** 1767 * Reset the latch data. Used when an allocation fails and the latch 1768 * needs to be re-added to the queue. 1769 */ 1770 private synchronized void reset() { 1771 _pair = null; 1772 _mayCreate = false; 1773 } 1774 } 1775 1776 1777 //--- private attributes --------------------------------------- 1778 1779 /** 1780 * The cap on the number of idle instances in the pool. 1781 * @see #setMaxIdle 1782 * @see #getMaxIdle 1783 */ 1784 private int _maxIdle = DEFAULT_MAX_IDLE; 1785 1786 /** 1787 * The cap on the minimum number of idle instances in the pool. 1788 * @see #setMinIdle 1789 * @see #getMinIdle 1790 */ 1791 private int _minIdle = DEFAULT_MIN_IDLE; 1792 1793 /** 1794 * The cap on the total number of active instances from the pool. 1795 * @see #setMaxActive 1796 * @see #getMaxActive 1797 */ 1798 private int _maxActive = DEFAULT_MAX_ACTIVE; 1799 1800 /** 1801 * The maximum amount of time (in millis) the 1802 * {@link #borrowObject} method should block before throwing 1803 * an exception when the pool is exhausted and the 1804 * {@link #getWhenExhaustedAction "when exhausted" action} is 1805 * {@link #WHEN_EXHAUSTED_BLOCK}. 1806 * 1807 * When less than or equal to 0, the {@link #borrowObject} method 1808 * may block indefinitely. 1809 * 1810 * @see #setMaxWait 1811 * @see #getMaxWait 1812 * @see #WHEN_EXHAUSTED_BLOCK 1813 * @see #setWhenExhaustedAction 1814 * @see #getWhenExhaustedAction 1815 */ 1816 private long _maxWait = DEFAULT_MAX_WAIT; 1817 1818 /** 1819 * The action to take when the {@link #borrowObject} method 1820 * is invoked when the pool is exhausted (the maximum number 1821 * of "active" objects has been reached). 1822 * 1823 * @see #WHEN_EXHAUSTED_BLOCK 1824 * @see #WHEN_EXHAUSTED_FAIL 1825 * @see #WHEN_EXHAUSTED_GROW 1826 * @see #DEFAULT_WHEN_EXHAUSTED_ACTION 1827 * @see #setWhenExhaustedAction 1828 * @see #getWhenExhaustedAction 1829 */ 1830 private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION; 1831 1832 /** 1833 * When <tt>true</tt>, objects will be 1834 * {@link PoolableObjectFactory#validateObject validated} 1835 * before being returned by the {@link #borrowObject} 1836 * method. If the object fails to validate, 1837 * it will be dropped from the pool, and we will attempt 1838 * to borrow another. 1839 * 1840 * @see #setTestOnBorrow 1841 * @see #getTestOnBorrow 1842 */ 1843 private volatile boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW; 1844 1845 /** 1846 * When <tt>true</tt>, objects will be 1847 * {@link PoolableObjectFactory#validateObject validated} 1848 * before being returned to the pool within the 1849 * {@link #returnObject}. 1850 * 1851 * @see #getTestOnReturn 1852 * @see #setTestOnReturn 1853 */ 1854 private volatile boolean _testOnReturn = DEFAULT_TEST_ON_RETURN; 1855 1856 /** 1857 * When <tt>true</tt>, objects will be 1858 * {@link PoolableObjectFactory#validateObject validated} 1859 * by the idle object evictor (if any). If an object 1860 * fails to validate, it will be dropped from the pool. 1861 * 1862 * @see #setTestWhileIdle 1863 * @see #getTestWhileIdle 1864 * @see #getTimeBetweenEvictionRunsMillis 1865 * @see #setTimeBetweenEvictionRunsMillis 1866 */ 1867 private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE; 1868 1869 /** 1870 * The number of milliseconds to sleep between runs of the 1871 * idle object evictor thread. 1872 * When non-positive, no idle object evictor thread will be 1873 * run. 1874 * 1875 * @see #setTimeBetweenEvictionRunsMillis 1876 * @see #getTimeBetweenEvictionRunsMillis 1877 */ 1878 private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; 1879 1880 /** 1881 * The max number of objects to examine during each run of the 1882 * idle object evictor thread (if any). 1883 * <p> 1884 * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt> 1885 * tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the 1886 * idle objects will be tested per run. 1887 * 1888 * @see #setNumTestsPerEvictionRun 1889 * @see #getNumTestsPerEvictionRun 1890 * @see #getTimeBetweenEvictionRunsMillis 1891 * @see #setTimeBetweenEvictionRunsMillis 1892 */ 1893 private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN; 1894 1895 /** 1896 * The minimum amount of time an object may sit idle in the pool 1897 * before it is eligible for eviction by the idle object evictor 1898 * (if any). 1899 * When non-positive, no objects will be evicted from the pool 1900 * due to idle time alone. 1901 * 1902 * @see #setMinEvictableIdleTimeMillis 1903 * @see #getMinEvictableIdleTimeMillis 1904 * @see #getTimeBetweenEvictionRunsMillis 1905 * @see #setTimeBetweenEvictionRunsMillis 1906 */ 1907 private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; 1908 1909 /** 1910 * The minimum amount of time an object may sit idle in the pool 1911 * before it is eligible for eviction by the idle object evictor 1912 * (if any), with the extra condition that at least 1913 * "minIdle" amount of object remain in the pool. 1914 * When non-positive, no objects will be evicted from the pool 1915 * due to idle time alone. 1916 * 1917 * @see #setSoftMinEvictableIdleTimeMillis 1918 * @see #getSoftMinEvictableIdleTimeMillis 1919 */ 1920 private long _softMinEvictableIdleTimeMillis = DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS; 1921 1922 /** Whether or not the pool behaves as a LIFO queue (last in first out) */ 1923 private boolean _lifo = DEFAULT_LIFO; 1924 1925 /** My pool. */ 1926 private CursorableLinkedList _pool = null; 1927 1928 /** Eviction cursor - keeps track of idle object evictor position */ 1929 private CursorableLinkedList.Cursor _evictionCursor = null; 1930 1931 /** My {@link PoolableObjectFactory}. */ 1932 private PoolableObjectFactory _factory = null; 1933 1934 /** 1935 * The number of objects {@link #borrowObject} borrowed 1936 * from the pool, but not yet returned. 1937 */ 1938 private int _numActive = 0; 1939 1940 /** 1941 * My idle object eviction {@link TimerTask}, if any. 1942 */ 1943 private Evictor _evictor = null; 1944 1945 /** 1946 * The number of objects subject to some form of internal processing 1947 * (usually creation or destruction) that should be included in the total 1948 * number of objects but are neither active nor idle. 1949 */ 1950 private int _numInternalProcessing = 0; 1951 1952 /** 1953 * Used to track the order in which threads call {@link #borrowObject()} so 1954 * that objects can be allocated in the order in which the threads requested 1955 * them. 1956 */ 1957 private LinkedList _allocationQueue = new LinkedList(); 1958 1959 }