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.PoolUtils;
031 import org.apache.commons.pool.PoolableObjectFactory;
032 import org.apache.commons.pool.impl.GenericKeyedObjectPool.ObjectTimestampPair;
033
034 /**
035 * A configurable {@link ObjectPool} implementation.
036 * <p>
037 * When coupled with the appropriate {@link PoolableObjectFactory},
038 * <tt>GenericObjectPool</tt> provides robust pooling functionality for
039 * arbitrary objects.
040 * <p>
041 * A <tt>GenericObjectPool</tt> provides a number of configurable parameters:
042 * <ul>
043 * <li>
044 * {@link #setMaxActive <i>maxActive</i>} controls the maximum number of
045 * objects that can be allocated by the pool (checked out to clients, or
046 * idle awaiting checkout) at a given time. When non-positive, there is no
047 * limit to the number of objects that can be managed by the pool at one time.
048 * When {@link #setMaxActive <i>maxActive</i>} is reached, the pool is said
049 * to be exhausted. The default setting for this parameter is 8.
050 * </li>
051 * <li>
052 * {@link #setMaxIdle <i>maxIdle</i>} controls the maximum number of objects
053 * that can sit idle in the pool at any time. When negative, there is no
054 * limit to the number of objects that may be idle at one time. The default
055 * setting for this parameter is 8.
056 * </li>
057 * <li>
058 * {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} specifies the
059 * behavior of the {@link #borrowObject} method when the pool is exhausted:
060 * <ul>
061 * <li>
062 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
063 * {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject} will throw
064 * a {@link NoSuchElementException}
065 * </li>
066 * <li>
067 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
068 * {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject} will create a new
069 * object and return it (essentially making {@link #setMaxActive <i>maxActive</i>}
070 * meaningless.)
071 * </li>
072 * <li>
073 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>}
074 * is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject} will block
075 * (invoke {@link Object#wait()}) until a new or idle object is available.
076 * If a positive {@link #setMaxWait <i>maxWait</i>}
077 * value is supplied, then {@link #borrowObject} will block for at
078 * most that many milliseconds, after which a {@link NoSuchElementException}
079 * will be thrown. If {@link #setMaxWait <i>maxWait</i>} is non-positive,
080 * the {@link #borrowObject} method will block indefinitely.
081 * </li>
082 * </ul>
083 * The default <code>whenExhaustedAction</code> setting is
084 * {@link #WHEN_EXHAUSTED_BLOCK} and the default <code>maxWait</code>
085 * setting is -1. By default, therefore, <code>borrowObject</code> will
086 * block indefinitely until an idle instance becomes available.
087 * </li>
088 * <li>
089 * When {@link #setTestOnBorrow <i>testOnBorrow</i>} is set, the pool will
090 * attempt to validate each object before it is returned from the
091 * {@link #borrowObject} method. (Using the provided factory's
092 * {@link PoolableObjectFactory#validateObject} method.) Objects that fail
093 * to validate will be dropped from the pool, and a different object will
094 * be borrowed. The default setting for this parameter is
095 * <code>false.</code>
096 * </li>
097 * <li>
098 * When {@link #setTestOnReturn <i>testOnReturn</i>} is set, the pool will
099 * attempt to validate each object before it is returned to the pool in the
100 * {@link #returnObject} method. (Using the provided factory's
101 * {@link PoolableObjectFactory#validateObject}
102 * method.) Objects that fail to validate will be dropped from the pool.
103 * The default setting for this parameter is <code>false.</code>
104 * </li>
105 * </ul>
106 * <p>
107 * Optionally, one may configure the pool to examine and possibly evict objects
108 * as they sit idle in the pool and to ensure that a minimum number of idle
109 * objects are available. This is performed by an "idle object eviction"
110 * thread, which runs asynchronously. Caution should be used when configuring
111 * this optional feature. Eviction runs contend with client threads for access
112 * to objects in the pool, so if they run too frequently performance issues may
113 * result. The idle object eviction thread may be configured using the following
114 * 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: 1206500 $ $Date: 2011-11-26 10:09:06 -0700 (Sat, 26 Nov 2011) $
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 void setMaxActive(int maxActive) {
628 synchronized(this) {
629 _maxActive = maxActive;
630 }
631 allocate();
632 }
633
634 /**
635 * Returns the action to take when the {@link #borrowObject} method
636 * is invoked when the pool is exhausted (the maximum number
637 * of "active" objects has been reached).
638 *
639 * @return one of {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW}
640 * @see #setWhenExhaustedAction
641 */
642 public synchronized byte getWhenExhaustedAction() {
643 return _whenExhaustedAction;
644 }
645
646 /**
647 * Sets the action to take when the {@link #borrowObject} method
648 * is invoked when the pool is exhausted (the maximum number
649 * of "active" objects has been reached).
650 *
651 * @param whenExhaustedAction the action code, which must be one of
652 * {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL},
653 * or {@link #WHEN_EXHAUSTED_GROW}
654 * @see #getWhenExhaustedAction
655 */
656 public void setWhenExhaustedAction(byte whenExhaustedAction) {
657 synchronized(this) {
658 switch(whenExhaustedAction) {
659 case WHEN_EXHAUSTED_BLOCK:
660 case WHEN_EXHAUSTED_FAIL:
661 case WHEN_EXHAUSTED_GROW:
662 _whenExhaustedAction = whenExhaustedAction;
663 break;
664 default:
665 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
666 }
667 }
668 allocate();
669 }
670
671
672 /**
673 * Returns the maximum amount of time (in milliseconds) the
674 * {@link #borrowObject} method should block before throwing
675 * an exception when the pool is exhausted and the
676 * {@link #setWhenExhaustedAction "when exhausted" action} is
677 * {@link #WHEN_EXHAUSTED_BLOCK}.
678 *
679 * When less than or equal to 0, the {@link #borrowObject} method
680 * may block indefinitely.
681 *
682 * @return maximum number of milliseconds to block when borrowing an object.
683 * @see #setMaxWait
684 * @see #setWhenExhaustedAction
685 * @see #WHEN_EXHAUSTED_BLOCK
686 */
687 public synchronized long getMaxWait() {
688 return _maxWait;
689 }
690
691 /**
692 * Sets the maximum amount of time (in milliseconds) the
693 * {@link #borrowObject} method should block before throwing
694 * an exception when the pool is exhausted and the
695 * {@link #setWhenExhaustedAction "when exhausted" action} is
696 * {@link #WHEN_EXHAUSTED_BLOCK}.
697 *
698 * When less than or equal to 0, the {@link #borrowObject} method
699 * may block indefinitely.
700 *
701 * @param maxWait maximum number of milliseconds to block when borrowing an object.
702 * @see #getMaxWait
703 * @see #setWhenExhaustedAction
704 * @see #WHEN_EXHAUSTED_BLOCK
705 */
706 public void setMaxWait(long maxWait) {
707 synchronized(this) {
708 _maxWait = maxWait;
709 }
710 allocate();
711 }
712
713 /**
714 * Returns the cap on the number of "idle" instances in the pool.
715 * @return the cap on the number of "idle" instances in the pool.
716 * @see #setMaxIdle
717 */
718 public synchronized int getMaxIdle() {
719 return _maxIdle;
720 }
721
722 /**
723 * Sets the cap on the number of "idle" instances in the pool.
724 * If maxIdle is set too low on heavily loaded systems it is possible you
725 * will see objects being destroyed and almost immediately new objects
726 * being created. This is a result of the active threads momentarily
727 * returning objects faster than they are requesting them them, causing the
728 * number of idle objects to rise above maxIdle. The best value for maxIdle
729 * for heavily loaded system will vary but the default is a good starting
730 * point.
731 * @param maxIdle The cap on the number of "idle" instances in the pool.
732 * Use a negative value to indicate an unlimited number of idle instances.
733 * @see #getMaxIdle
734 */
735 public void setMaxIdle(int maxIdle) {
736 synchronized(this) {
737 _maxIdle = maxIdle;
738 }
739 allocate();
740 }
741
742 /**
743 * Sets the minimum number of objects allowed in the pool
744 * before the evictor thread (if active) spawns new objects.
745 * Note that no objects are created when
746 * <code>numActive + numIdle >= maxActive.</code>
747 * This setting has no effect if the idle object evictor is disabled
748 * (i.e. if <code>timeBetweenEvictionRunsMillis <= 0</code>).
749 *
750 * @param minIdle The minimum number of objects.
751 * @see #getMinIdle
752 * @see #getTimeBetweenEvictionRunsMillis()
753 */
754 public void setMinIdle(int minIdle) {
755 synchronized(this) {
756 _minIdle = minIdle;
757 }
758 allocate();
759 }
760
761 /**
762 * Returns the minimum number of objects allowed in the pool
763 * before the evictor thread (if active) spawns new objects.
764 * (Note no objects are created when: numActive + numIdle >= maxActive)
765 *
766 * @return The minimum number of objects.
767 * @see #setMinIdle
768 */
769 public synchronized int getMinIdle() {
770 return _minIdle;
771 }
772
773 /**
774 * When <tt>true</tt>, objects will be
775 * {@link PoolableObjectFactory#validateObject validated}
776 * before being returned by the {@link #borrowObject}
777 * method. If the object fails to validate,
778 * it will be dropped from the pool, and we will attempt
779 * to borrow another.
780 *
781 * @return <code>true</code> if objects are validated before being borrowed.
782 * @see #setTestOnBorrow
783 */
784 public boolean getTestOnBorrow() {
785 return _testOnBorrow;
786 }
787
788 /**
789 * When <tt>true</tt>, objects will be
790 * {@link PoolableObjectFactory#validateObject validated}
791 * before being returned by the {@link #borrowObject}
792 * method. If the object fails to validate,
793 * it will be dropped from the pool, and we will attempt
794 * to borrow another.
795 *
796 * @param testOnBorrow <code>true</code> if objects should be validated before being borrowed.
797 * @see #getTestOnBorrow
798 */
799 public void setTestOnBorrow(boolean testOnBorrow) {
800 _testOnBorrow = testOnBorrow;
801 }
802
803 /**
804 * When <tt>true</tt>, objects will be
805 * {@link PoolableObjectFactory#validateObject validated}
806 * before being returned to the pool within the
807 * {@link #returnObject}.
808 *
809 * @return <code>true</code> when objects will be validated after returned to {@link #returnObject}.
810 * @see #setTestOnReturn
811 */
812 public boolean getTestOnReturn() {
813 return _testOnReturn;
814 }
815
816 /**
817 * When <tt>true</tt>, objects will be
818 * {@link PoolableObjectFactory#validateObject validated}
819 * before being returned to the pool within the
820 * {@link #returnObject}.
821 *
822 * @param testOnReturn <code>true</code> so objects will be validated after returned to {@link #returnObject}.
823 * @see #getTestOnReturn
824 */
825 public void setTestOnReturn(boolean testOnReturn) {
826 _testOnReturn = testOnReturn;
827 }
828
829 /**
830 * Returns the number of milliseconds to sleep between runs of the
831 * idle object evictor thread.
832 * When non-positive, no idle object evictor thread will be
833 * run.
834 *
835 * @return number of milliseconds to sleep between evictor runs.
836 * @see #setTimeBetweenEvictionRunsMillis
837 */
838 public synchronized long getTimeBetweenEvictionRunsMillis() {
839 return _timeBetweenEvictionRunsMillis;
840 }
841
842 /**
843 * Sets the number of milliseconds to sleep between runs of the
844 * idle object evictor thread.
845 * When non-positive, no idle object evictor thread will be
846 * run.
847 *
848 * @param timeBetweenEvictionRunsMillis number of milliseconds to sleep between evictor runs.
849 * @see #getTimeBetweenEvictionRunsMillis
850 */
851 public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
852 _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
853 startEvictor(_timeBetweenEvictionRunsMillis);
854 }
855
856 /**
857 * Returns the max number of objects to examine during each run of the
858 * idle object evictor thread (if any).
859 *
860 * @return max number of objects to examine during each evictor run.
861 * @see #setNumTestsPerEvictionRun
862 * @see #setTimeBetweenEvictionRunsMillis
863 */
864 public synchronized int getNumTestsPerEvictionRun() {
865 return _numTestsPerEvictionRun;
866 }
867
868 /**
869 * Sets the max number of objects to examine during each run of the
870 * idle object evictor thread (if any).
871 * <p>
872 * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
873 * tests will be run. That is, when the value is <i>-n</i>, roughly one <i>n</i>th of the
874 * idle objects will be tested per run. When the value is positive, the number of tests
875 * actually performed in each run will be the minimum of this value and the number of instances
876 * idle in the pool.
877 *
878 * @param numTestsPerEvictionRun max number of objects to examine during each evictor run.
879 * @see #getNumTestsPerEvictionRun
880 * @see #setTimeBetweenEvictionRunsMillis
881 */
882 public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
883 _numTestsPerEvictionRun = numTestsPerEvictionRun;
884 }
885
886 /**
887 * Returns the minimum amount of time an object may sit idle in the pool
888 * before it is eligible for eviction by the idle object evictor
889 * (if any).
890 *
891 * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction.
892 * @see #setMinEvictableIdleTimeMillis
893 * @see #setTimeBetweenEvictionRunsMillis
894 */
895 public synchronized long getMinEvictableIdleTimeMillis() {
896 return _minEvictableIdleTimeMillis;
897 }
898
899 /**
900 * Sets the minimum amount of time an object may sit idle in the pool
901 * before it is eligible for eviction by the idle object evictor
902 * (if any).
903 * When non-positive, no objects will be evicted from the pool
904 * due to idle time alone.
905 * @param minEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before
906 * it is eligible for eviction.
907 * @see #getMinEvictableIdleTimeMillis
908 * @see #setTimeBetweenEvictionRunsMillis
909 */
910 public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
911 _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
912 }
913
914 /**
915 * Returns the minimum amount of time an object may sit idle in the pool
916 * before it is eligible for eviction by the idle object evictor
917 * (if any), with the extra condition that at least
918 * "minIdle" amount of object remain in the pool.
919 *
920 * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction.
921 * @since Pool 1.3
922 * @see #setSoftMinEvictableIdleTimeMillis
923 */
924 public synchronized long getSoftMinEvictableIdleTimeMillis() {
925 return _softMinEvictableIdleTimeMillis;
926 }
927
928 /**
929 * Sets the minimum amount of time an object may sit idle in the pool
930 * before it is eligible for eviction by the idle object evictor
931 * (if any), with the extra condition that at least
932 * "minIdle" object instances remain in the pool.
933 * When non-positive, no objects will be evicted from the pool
934 * due to idle time alone.
935 *
936 * @param softMinEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before
937 * it is eligible for eviction.
938 * @since Pool 1.3
939 * @see #getSoftMinEvictableIdleTimeMillis
940 */
941 public synchronized void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis) {
942 _softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
943 }
944
945 /**
946 * When <tt>true</tt>, objects will be
947 * {@link PoolableObjectFactory#validateObject validated}
948 * by the idle object evictor (if any). If an object
949 * fails to validate, it will be dropped from the pool.
950 *
951 * @return <code>true</code> when objects will be validated by the evictor.
952 * @see #setTestWhileIdle
953 * @see #setTimeBetweenEvictionRunsMillis
954 */
955 public synchronized boolean getTestWhileIdle() {
956 return _testWhileIdle;
957 }
958
959 /**
960 * When <tt>true</tt>, objects will be
961 * {@link PoolableObjectFactory#validateObject validated}
962 * by the idle object evictor (if any). If an object
963 * fails to validate, it will be dropped from the pool.
964 *
965 * @param testWhileIdle <code>true</code> so objects will be validated by the evictor.
966 * @see #getTestWhileIdle
967 * @see #setTimeBetweenEvictionRunsMillis
968 */
969 public synchronized void setTestWhileIdle(boolean testWhileIdle) {
970 _testWhileIdle = testWhileIdle;
971 }
972
973 /**
974 * Whether or not the idle object pool acts as a LIFO queue. True means
975 * that borrowObject returns the most recently used ("last in") idle object
976 * in the pool (if there are idle instances available). False means that
977 * the pool behaves as a FIFO queue - objects are taken from the idle object
978 * pool in the order that they are returned to the pool.
979 *
980 * @return <code>true</true> if the pool is configured to act as a LIFO queue
981 * @since 1.4
982 */
983 public synchronized boolean getLifo() {
984 return _lifo;
985 }
986
987 /**
988 * Sets the LIFO property of the pool. True means that borrowObject returns
989 * the most recently used ("last in") idle object in the pool (if there are
990 * idle instances available). False means that the pool behaves as a FIFO
991 * queue - objects are taken from the idle object pool in the order that
992 * they are returned to the pool.
993 *
994 * @param lifo the new value for the LIFO property
995 * @since 1.4
996 */
997 public synchronized void setLifo(boolean lifo) {
998 this._lifo = lifo;
999 }
1000
1001 /**
1002 * Sets my configuration.
1003 *
1004 * @param conf configuration to use.
1005 * @see GenericObjectPool.Config
1006 */
1007 public void setConfig(GenericObjectPool.Config conf) {
1008 synchronized (this) {
1009 setMaxIdle(conf.maxIdle);
1010 setMinIdle(conf.minIdle);
1011 setMaxActive(conf.maxActive);
1012 setMaxWait(conf.maxWait);
1013 setWhenExhaustedAction(conf.whenExhaustedAction);
1014 setTestOnBorrow(conf.testOnBorrow);
1015 setTestOnReturn(conf.testOnReturn);
1016 setTestWhileIdle(conf.testWhileIdle);
1017 setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun);
1018 setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
1019 setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
1020 setSoftMinEvictableIdleTimeMillis(conf.softMinEvictableIdleTimeMillis);
1021 setLifo(conf.lifo);
1022 }
1023 allocate();
1024 }
1025
1026 //-- ObjectPool methods ------------------------------------------
1027
1028 /**
1029 * <p>Borrows an object from the pool.</p>
1030 *
1031 * <p>If there is an idle instance available in the pool, then either the most-recently returned
1032 * (if {@link #getLifo() lifo} == true) or "oldest" (lifo == false) instance sitting idle in the pool
1033 * will be activated and returned. If activation fails, or {@link #getTestOnBorrow() testOnBorrow} is set
1034 * to true and validation fails, the instance is destroyed and the next available instance is examined.
1035 * This continues until either a valid instance is returned or there are no more idle instances available.</p>
1036 *
1037 * <p>If there are no idle instances available in the pool, behavior depends on the {@link #getMaxActive() maxActive}
1038 * and (if applicable) {@link #getWhenExhaustedAction() whenExhaustedAction} and {@link #getMaxWait() maxWait}
1039 * properties. If the number of instances checked out from the pool is less than <code>maxActive,</code> a new
1040 * instance is created, activated and (if applicable) validated and returned to the caller.</p>
1041 *
1042 * <p>If the pool is exhausted (no available idle instances and no capacity to create new ones),
1043 * this method will either block ({@link #WHEN_EXHAUSTED_BLOCK}), throw a <code>NoSuchElementException</code>
1044 * ({@link #WHEN_EXHAUSTED_FAIL}), or grow ({@link #WHEN_EXHAUSTED_GROW} - ignoring maxActive).
1045 * The length of time that this method will block when <code>whenExhaustedAction == WHEN_EXHAUSTED_BLOCK</code>
1046 * is determined by the {@link #getMaxWait() maxWait} property.</p>
1047 *
1048 * <p>When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances
1049 * to become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads receive
1050 * available instances in request arrival order.</p>
1051 *
1052 * @return object instance
1053 * @throws NoSuchElementException if an instance cannot be returned
1054 */
1055 public Object borrowObject() throws Exception {
1056 long starttime = System.currentTimeMillis();
1057 Latch latch = new Latch();
1058 byte whenExhaustedAction;
1059 long maxWait;
1060 synchronized (this) {
1061 // Get local copy of current config. Can't sync when used later as
1062 // it can result in a deadlock. Has the added advantage that config
1063 // is consistent for entire method execution
1064 whenExhaustedAction = _whenExhaustedAction;
1065 maxWait = _maxWait;
1066
1067 // Add this request to the queue
1068 _allocationQueue.add(latch);
1069 }
1070 // Work the allocation queue, allocating idle instances and
1071 // instance creation permits in request arrival order
1072 allocate();
1073
1074 for(;;) {
1075 synchronized (this) {
1076 assertOpen();
1077 }
1078
1079 // If no object was allocated from the pool above
1080 if(latch.getPair() == null) {
1081 // check if we were allowed to create one
1082 if(latch.mayCreate()) {
1083 // allow new object to be created
1084 } else {
1085 // the pool is exhausted
1086 switch(whenExhaustedAction) {
1087 case WHEN_EXHAUSTED_GROW:
1088 // allow new object to be created
1089 synchronized (this) {
1090 // Make sure another thread didn't allocate us an object
1091 // or permit a new object to be created
1092 if (latch.getPair() == null && !latch.mayCreate()) {
1093 _allocationQueue.remove(latch);
1094 _numInternalProcessing++;
1095 }
1096 }
1097 break;
1098 case WHEN_EXHAUSTED_FAIL:
1099 synchronized (this) {
1100 // Make sure allocate hasn't already assigned an object
1101 // in a different thread or permitted a new object to be created
1102 if (latch.getPair() != null || latch.mayCreate()) {
1103 break;
1104 }
1105 _allocationQueue.remove(latch);
1106 }
1107 throw new NoSuchElementException("Pool exhausted");
1108 case WHEN_EXHAUSTED_BLOCK:
1109 try {
1110 synchronized (latch) {
1111 // Before we wait, make sure another thread didn't allocate us an object
1112 // or permit a new object to be created
1113 if (latch.getPair() == null && !latch.mayCreate()) {
1114 if(maxWait <= 0) {
1115 latch.wait();
1116 } else {
1117 // this code may be executed again after a notify then continue cycle
1118 // so, need to calculate the amount of time to wait
1119 final long elapsed = (System.currentTimeMillis() - starttime);
1120 final long waitTime = maxWait - elapsed;
1121 if (waitTime > 0)
1122 {
1123 latch.wait(waitTime);
1124 }
1125 }
1126 } else {
1127 break;
1128 }
1129 }
1130 // see if we were awakened by a closing pool
1131 if(isClosed() == true) {
1132 throw new IllegalStateException("Pool closed");
1133 }
1134 } catch(InterruptedException e) {
1135 boolean doAllocate = false;
1136 synchronized(this) {
1137 // Need to handle the all three possibilities
1138 if (latch.getPair() == null && !latch.mayCreate()) {
1139 // Case 1: latch still in allocation queue
1140 // Remove latch from the allocation queue
1141 _allocationQueue.remove(latch);
1142 } else if (latch.getPair() == null && latch.mayCreate()) {
1143 // Case 2: latch has been given permission to create
1144 // a new object
1145 _numInternalProcessing--;
1146 doAllocate = true;
1147 } else {
1148 // Case 3: An object has been allocated
1149 _numInternalProcessing--;
1150 _numActive++;
1151 returnObject(latch.getPair().getValue());
1152 }
1153 }
1154 if (doAllocate) {
1155 allocate();
1156 }
1157 Thread.currentThread().interrupt();
1158 throw e;
1159 }
1160 if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
1161 synchronized(this) {
1162 // Make sure allocate hasn't already assigned an object
1163 // in a different thread or permitted a new object to be created
1164 if (latch.getPair() == null && !latch.mayCreate()) {
1165 // Remove latch from the allocation queue
1166 _allocationQueue.remove(latch);
1167 } else {
1168 break;
1169 }
1170 }
1171 throw new NoSuchElementException("Timeout waiting for idle object");
1172 } else {
1173 continue; // keep looping
1174 }
1175 default:
1176 throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction +
1177 " not recognized.");
1178 }
1179 }
1180 }
1181
1182 boolean newlyCreated = false;
1183 if(null == latch.getPair()) {
1184 try {
1185 Object obj = _factory.makeObject();
1186 latch.setPair(new ObjectTimestampPair(obj));
1187 newlyCreated = true;
1188 } finally {
1189 if (!newlyCreated) {
1190 // object cannot be created
1191 synchronized (this) {
1192 _numInternalProcessing--;
1193 // No need to reset latch - about to throw exception
1194 }
1195 allocate();
1196 }
1197 }
1198 }
1199 // activate & validate the object
1200 try {
1201 _factory.activateObject(latch.getPair().value);
1202 if(_testOnBorrow &&
1203 !_factory.validateObject(latch.getPair().value)) {
1204 throw new Exception("ValidateObject failed");
1205 }
1206 synchronized(this) {
1207 _numInternalProcessing--;
1208 _numActive++;
1209 }
1210 return latch.getPair().value;
1211 }
1212 catch (Throwable e) {
1213 PoolUtils.checkRethrow(e);
1214 // object cannot be activated or is invalid
1215 try {
1216 _factory.destroyObject(latch.getPair().value);
1217 } catch (Throwable e2) {
1218 PoolUtils.checkRethrow(e2);
1219 // cannot destroy broken object
1220 }
1221 synchronized (this) {
1222 _numInternalProcessing--;
1223 if (!newlyCreated) {
1224 latch.reset();
1225 _allocationQueue.add(0, latch);
1226 }
1227 }
1228 allocate();
1229 if(newlyCreated) {
1230 throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
1231 }
1232 else {
1233 continue; // keep looping
1234 }
1235 }
1236 }
1237 }
1238
1239 /**
1240 * Allocate available instances to latches in the allocation queue. Then
1241 * set _mayCreate to true for as many additional latches remaining in queue
1242 * as _maxActive allows. While it is safe for GOP, for consistency with GKOP
1243 * this method should not be called from inside a sync block.
1244 */
1245 private synchronized void allocate() {
1246 if (isClosed()) return;
1247
1248 // First use any objects in the pool to clear the queue
1249 for (;;) {
1250 if (!_pool.isEmpty() && !_allocationQueue.isEmpty()) {
1251 Latch latch = (Latch) _allocationQueue.removeFirst();
1252 latch.setPair((ObjectTimestampPair) _pool.removeFirst());
1253 _numInternalProcessing++;
1254 synchronized (latch) {
1255 latch.notify();
1256 }
1257 } else {
1258 break;
1259 }
1260 }
1261
1262 // Second utilise any spare capacity to create new objects
1263 for(;;) {
1264 if((!_allocationQueue.isEmpty()) && (_maxActive < 0 || (_numActive + _numInternalProcessing) < _maxActive)) {
1265 Latch latch = (Latch) _allocationQueue.removeFirst();
1266 latch.setMayCreate(true);
1267 _numInternalProcessing++;
1268 synchronized (latch) {
1269 latch.notify();
1270 }
1271 } else {
1272 break;
1273 }
1274 }
1275 }
1276
1277 /**
1278 * {@inheritDoc}
1279 * <p>Activation of this method decrements the active count and attempts to destroy the instance.</p>
1280 *
1281 * @throws Exception if the configured {@link PoolableObjectFactory} throws an exception destroying obj
1282 */
1283 public void invalidateObject(Object obj) throws Exception {
1284 try {
1285 if (_factory != null) {
1286 _factory.destroyObject(obj);
1287 }
1288 } finally {
1289 synchronized (this) {
1290 _numActive--;
1291 }
1292 allocate();
1293 }
1294 }
1295
1296 /**
1297 * Clears any objects sitting idle in the pool by removing them from the
1298 * idle instance pool and then invoking the configured
1299 * {@link PoolableObjectFactory#destroyObject(Object)} method on each idle
1300 * instance.
1301 *
1302 * <p> Implementation notes:
1303 * <ul><li>This method does not destroy or effect in any way instances that are
1304 * checked out of the pool when it is invoked.</li>
1305 * <li>Invoking this method does not prevent objects being
1306 * returned to the idle instance pool, even during its execution. It locks
1307 * the pool only during instance removal. Additional instances may be returned
1308 * while removed items are being destroyed.</li>
1309 * <li>Exceptions encountered destroying idle instances are swallowed.</li></ul></p>
1310 */
1311 public void clear() {
1312 List toDestroy = new ArrayList();
1313
1314 synchronized(this) {
1315 toDestroy.addAll(_pool);
1316 _numInternalProcessing = _numInternalProcessing + _pool._size;
1317 _pool.clear();
1318 }
1319 destroy(toDestroy, _factory);
1320 }
1321
1322 /**
1323 * Private method to destroy all the objects in a collection using the
1324 * supplied object factory. Assumes that objects in the collection are
1325 * instances of ObjectTimestampPair and that the object instances that
1326 * they wrap were created by the factory.
1327 *
1328 * @param c Collection of objects to destroy
1329 * @param factory PoolableConnectionFactory used to destroy the objects
1330 */
1331 private void destroy(Collection c, PoolableObjectFactory factory) {
1332 for (Iterator it = c.iterator(); it.hasNext();) {
1333 try {
1334 factory.destroyObject(((ObjectTimestampPair)(it.next())).value);
1335 } catch(Exception e) {
1336 // ignore error, keep destroying the rest
1337 } finally {
1338 synchronized(this) {
1339 _numInternalProcessing--;
1340 }
1341 allocate();
1342 }
1343 }
1344 }
1345
1346 /**
1347 * Return the number of instances currently borrowed from this pool.
1348 *
1349 * @return the number of instances currently borrowed from this pool
1350 */
1351 public synchronized int getNumActive() {
1352 return _numActive;
1353 }
1354
1355 /**
1356 * Return the number of instances currently idle in this pool.
1357 *
1358 * @return the number of instances currently idle in this pool
1359 */
1360 public synchronized int getNumIdle() {
1361 return _pool.size();
1362 }
1363
1364 /**
1365 * <p>Returns an object instance to the pool.</p>
1366 *
1367 * <p>If {@link #getMaxIdle() maxIdle} is set to a positive value and the number of idle instances
1368 * has reached this value, the returning instance is destroyed.</p>
1369 *
1370 * <p>If {@link #getTestOnReturn() testOnReturn} == true, the returning instance is validated before being returned
1371 * to the idle instance pool. In this case, if validation fails, the instance is destroyed.</p>
1372 *
1373 * <p><strong>Note: </strong> There is no guard to prevent an object
1374 * being returned to the pool multiple times. Clients are expected to
1375 * discard references to returned objects and ensure that an object is not
1376 * returned to the pool multiple times in sequence (i.e., without being
1377 * borrowed again between returns). Violating this contract will result in
1378 * the same object appearing multiple times in the pool and pool counters
1379 * (numActive, numIdle) returning incorrect values.</p>
1380 *
1381 * @param obj instance to return to the pool
1382 */
1383 public void returnObject(Object obj) throws Exception {
1384 try {
1385 addObjectToPool(obj, true);
1386 } catch (Exception e) {
1387 if (_factory != null) {
1388 try {
1389 _factory.destroyObject(obj);
1390 } catch (Exception e2) {
1391 // swallowed
1392 }
1393 // TODO: Correctness here depends on control in addObjectToPool.
1394 // These two methods should be refactored, removing the
1395 // "behavior flag", decrementNumActive, from addObjectToPool.
1396 synchronized(this) {
1397 _numActive--;
1398 }
1399 allocate();
1400 }
1401 }
1402 }
1403
1404 /**
1405 * <p>Adds an object to the pool.</p>
1406 *
1407 * <p>Validates the object if testOnReturn == true and passivates it before returning it to the pool.
1408 * if validation or passivation fails, or maxIdle is set and there is no room in the pool, the instance
1409 * is destroyed.</p>
1410 *
1411 * <p>Calls {@link #allocate()} on successful completion</p>
1412 *
1413 * @param obj instance to add to the pool
1414 * @param decrementNumActive whether or not to decrement the active count
1415 * @throws Exception
1416 */
1417 private void addObjectToPool(Object obj, boolean decrementNumActive) throws Exception {
1418 boolean success = true;
1419 if(_testOnReturn && !(_factory.validateObject(obj))) {
1420 success = false;
1421 } else {
1422 _factory.passivateObject(obj);
1423 }
1424
1425 boolean shouldDestroy = !success;
1426
1427 // Add instance to pool if there is room and it has passed validation
1428 // (if testOnreturn is set)
1429 boolean doAllocate = false;
1430 synchronized (this) {
1431 if (isClosed()) {
1432 shouldDestroy = true;
1433 } else {
1434 if((_maxIdle >= 0) && (_pool.size() >= _maxIdle)) {
1435 shouldDestroy = true;
1436 } else if(success) {
1437 // borrowObject always takes the first element from the queue,
1438 // so for LIFO, push on top, FIFO add to end
1439 if (_lifo) {
1440 _pool.addFirst(new ObjectTimestampPair(obj));
1441 } else {
1442 _pool.addLast(new ObjectTimestampPair(obj));
1443 }
1444 if (decrementNumActive) {
1445 _numActive--;
1446 }
1447 doAllocate = true;
1448 }
1449 }
1450 }
1451 if (doAllocate) {
1452 allocate();
1453 }
1454
1455 // Destroy the instance if necessary
1456 if(shouldDestroy) {
1457 try {
1458 _factory.destroyObject(obj);
1459 } catch(Exception e) {
1460 // ignored
1461 }
1462 // Decrement active count *after* destroy if applicable
1463 if (decrementNumActive) {
1464 synchronized(this) {
1465 _numActive--;
1466 }
1467 allocate();
1468 }
1469 }
1470
1471 }
1472
1473 /**
1474 * <p>Closes the pool. Once the pool is closed, {@link #borrowObject()}
1475 * will fail with IllegalStateException, but {@link #returnObject(Object)} and
1476 * {@link #invalidateObject(Object)} will continue to work, with returned objects
1477 * destroyed on return.</p>
1478 *
1479 * <p>Destroys idle instances in the pool by invoking {@link #clear()}.</p>
1480 *
1481 * @throws Exception
1482 */
1483 public void close() throws Exception {
1484 super.close();
1485 synchronized (this) {
1486 clear();
1487 startEvictor(-1L);
1488
1489 while(_allocationQueue.size() > 0) {
1490 Latch l = (Latch) _allocationQueue.removeFirst();
1491
1492 synchronized (l) {
1493 // notify the waiting thread
1494 l.notify();
1495 }
1496 }
1497 }
1498 }
1499
1500 /**
1501 * Sets the {@link PoolableObjectFactory factory} this pool uses
1502 * to create new instances. Trying to change
1503 * the <code>factory</code> while there are borrowed objects will
1504 * throw an {@link IllegalStateException}. If there are instances idle
1505 * in the pool when this method is invoked, these will be destroyed
1506 * using the original factory.
1507 *
1508 * @param factory the {@link PoolableObjectFactory} used to create new instances.
1509 * @throws IllegalStateException when the factory cannot be set at this time
1510 * @deprecated to be removed in version 2.0
1511 */
1512 public void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
1513 List toDestroy = new ArrayList();
1514 final PoolableObjectFactory oldFactory = _factory;
1515 synchronized (this) {
1516 assertOpen();
1517 if(0 < getNumActive()) {
1518 throw new IllegalStateException("Objects are already active");
1519 } else {
1520 toDestroy.addAll(_pool);
1521 _numInternalProcessing = _numInternalProcessing + _pool._size;
1522 _pool.clear();
1523 }
1524 _factory = factory;
1525 }
1526 destroy(toDestroy, oldFactory);
1527 }
1528
1529 /**
1530 * <p>Perform <code>numTests</code> idle object eviction tests, evicting
1531 * examined objects that meet the criteria for eviction. If
1532 * <code>testWhileIdle</code> is true, examined objects are validated
1533 * when visited (and removed if invalid); otherwise only objects that
1534 * have been idle for more than <code>minEvicableIdletimeMillis</code>
1535 * are removed.</p>
1536 *
1537 * <p>Successive activations of this method examine objects in
1538 * in sequence, cycling through objects in oldest-to-youngest order.</p>
1539 *
1540 * @throws Exception if the pool is closed or eviction fails.
1541 */
1542 public void evict() throws Exception {
1543 assertOpen();
1544 synchronized (this) {
1545 if(_pool.isEmpty()) {
1546 return;
1547 }
1548 if (null == _evictionCursor) {
1549 _evictionCursor = (_pool.cursor(_lifo ? _pool.size() : 0));
1550 }
1551 }
1552
1553 for (int i=0,m=getNumTests();i<m;i++) {
1554 final ObjectTimestampPair pair;
1555 synchronized (this) {
1556 if ((_lifo && !_evictionCursor.hasPrevious()) ||
1557 !_lifo && !_evictionCursor.hasNext()) {
1558 _evictionCursor.close();
1559 _evictionCursor = _pool.cursor(_lifo ? _pool.size() : 0);
1560 }
1561
1562 pair = _lifo ?
1563 (ObjectTimestampPair) _evictionCursor.previous() :
1564 (ObjectTimestampPair) _evictionCursor.next();
1565
1566 _evictionCursor.remove();
1567 _numInternalProcessing++;
1568 }
1569
1570 boolean removeObject = false;
1571 final long idleTimeMilis = System.currentTimeMillis() - pair.tstamp;
1572 if ((getMinEvictableIdleTimeMillis() > 0) &&
1573 (idleTimeMilis > getMinEvictableIdleTimeMillis())) {
1574 removeObject = true;
1575 } else if ((getSoftMinEvictableIdleTimeMillis() > 0) &&
1576 (idleTimeMilis > getSoftMinEvictableIdleTimeMillis()) &&
1577 ((getNumIdle() + 1)> getMinIdle())) { // +1 accounts for object we are processing
1578 removeObject = true;
1579 }
1580 if(getTestWhileIdle() && !removeObject) {
1581 boolean active = false;
1582 try {
1583 _factory.activateObject(pair.value);
1584 active = true;
1585 } catch(Exception e) {
1586 removeObject=true;
1587 }
1588 if(active) {
1589 if(!_factory.validateObject(pair.value)) {
1590 removeObject=true;
1591 } else {
1592 try {
1593 _factory.passivateObject(pair.value);
1594 } catch(Exception e) {
1595 removeObject=true;
1596 }
1597 }
1598 }
1599 }
1600
1601 if (removeObject) {
1602 try {
1603 _factory.destroyObject(pair.value);
1604 } catch(Exception e) {
1605 // ignored
1606 }
1607 }
1608 synchronized (this) {
1609 if(!removeObject) {
1610 _evictionCursor.add(pair);
1611 if (_lifo) {
1612 // Skip over the element we just added back
1613 _evictionCursor.previous();
1614 }
1615 }
1616 _numInternalProcessing--;
1617 }
1618 }
1619 allocate();
1620 }
1621
1622 /**
1623 * Check to see if we are below our minimum number of objects
1624 * if so enough to bring us back to our minimum.
1625 *
1626 * @throws Exception when {@link #addObject()} fails.
1627 */
1628 private void ensureMinIdle() throws Exception {
1629 // this method isn't synchronized so the
1630 // calculateDeficit is done at the beginning
1631 // as a loop limit and a second time inside the loop
1632 // to stop when another thread already returned the
1633 // needed objects
1634 int objectDeficit = calculateDeficit(false);
1635 for ( int j = 0 ; j < objectDeficit && calculateDeficit(true) > 0 ; j++ ) {
1636 try {
1637 addObject();
1638 } finally {
1639 synchronized (this) {
1640 _numInternalProcessing--;
1641 }
1642 allocate();
1643 }
1644 }
1645 }
1646
1647 /**
1648 * This returns the number of objects to create during the pool
1649 * sustain cycle. This will ensure that the minimum number of idle
1650 * instances is maintained without going past the maxActive value.
1651 *
1652 * @param incrementInternal - Should the count of objects currently under
1653 * some form of internal processing be
1654 * incremented?
1655 * @return The number of objects to be created
1656 */
1657 private synchronized int calculateDeficit(boolean incrementInternal) {
1658 int objectDeficit = getMinIdle() - getNumIdle();
1659 if (_maxActive > 0) {
1660 int growLimit = Math.max(0,
1661 getMaxActive() - getNumActive() - getNumIdle() - _numInternalProcessing);
1662 objectDeficit = Math.min(objectDeficit, growLimit);
1663 }
1664 if (incrementInternal && objectDeficit >0) {
1665 _numInternalProcessing++;
1666 }
1667 return objectDeficit;
1668 }
1669
1670 /**
1671 * Create an object, and place it into the pool.
1672 * addObject() is useful for "pre-loading" a pool with idle objects.
1673 */
1674 public void addObject() throws Exception {
1675 assertOpen();
1676 if (_factory == null) {
1677 throw new IllegalStateException("Cannot add objects without a factory.");
1678 }
1679 Object obj = _factory.makeObject();
1680 try {
1681 assertOpen();
1682 addObjectToPool(obj, false);
1683 } catch (IllegalStateException ex) { // Pool closed
1684 try {
1685 _factory.destroyObject(obj);
1686 } catch (Exception ex2) {
1687 // swallow
1688 }
1689 throw ex;
1690 }
1691 }
1692
1693 //--- non-public methods ----------------------------------------
1694
1695 /**
1696 * Start the eviction thread or service, or when
1697 * <i>delay</i> is non-positive, stop it
1698 * if it is already running.
1699 *
1700 * @param delay milliseconds between evictor runs.
1701 */
1702 protected synchronized void startEvictor(long delay) {
1703 if(null != _evictor) {
1704 EvictionTimer.cancel(_evictor);
1705 _evictor = null;
1706 }
1707 if(delay > 0) {
1708 _evictor = new Evictor();
1709 EvictionTimer.schedule(_evictor, delay, delay);
1710 }
1711 }
1712
1713 /**
1714 * Returns pool info including {@link #getNumActive()}, {@link #getNumIdle()}
1715 * and a list of objects idle in the pool with their idle times.
1716 *
1717 * @return string containing debug information
1718 */
1719 synchronized String debugInfo() {
1720 StringBuffer buf = new StringBuffer();
1721 buf.append("Active: ").append(getNumActive()).append("\n");
1722 buf.append("Idle: ").append(getNumIdle()).append("\n");
1723 buf.append("Idle Objects:\n");
1724 Iterator it = _pool.iterator();
1725 long time = System.currentTimeMillis();
1726 while(it.hasNext()) {
1727 ObjectTimestampPair pair = (ObjectTimestampPair)(it.next());
1728 buf.append("\t").append(pair.value).append("\t").append(time - pair.tstamp).append("\n");
1729 }
1730 return buf.toString();
1731 }
1732
1733 /**
1734 * Returns the number of tests to be performed in an Evictor run,
1735 * based on the current value of <code>numTestsPerEvictionRun</code>
1736 * and the number of idle instances in the pool.
1737 *
1738 * @see #setNumTestsPerEvictionRun
1739 * @return the number of tests for the Evictor to run
1740 */
1741 private int getNumTests() {
1742 if(_numTestsPerEvictionRun >= 0) {
1743 return Math.min(_numTestsPerEvictionRun, _pool.size());
1744 } else {
1745 return(int)(Math.ceil(_pool.size()/Math.abs((double)_numTestsPerEvictionRun)));
1746 }
1747 }
1748
1749 //--- inner classes ----------------------------------------------
1750
1751 /**
1752 * The idle object evictor {@link TimerTask}.
1753 * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis
1754 */
1755 private class Evictor extends TimerTask {
1756 /**
1757 * Run pool maintenance. Evict objects qualifying for eviction and then
1758 * invoke {@link GenericObjectPool#ensureMinIdle()}.
1759 */
1760 public void run() {
1761 try {
1762 evict();
1763 } catch(Exception e) {
1764 // ignored
1765 } catch(OutOfMemoryError oome) {
1766 // Log problem but give evictor thread a chance to continue in
1767 // case error is recoverable
1768 oome.printStackTrace(System.err);
1769 }
1770 try {
1771 ensureMinIdle();
1772 } catch(Exception e) {
1773 // ignored
1774 }
1775 }
1776 }
1777
1778 /**
1779 * A simple "struct" encapsulating the
1780 * configuration information for a {@link GenericObjectPool}.
1781 * @see GenericObjectPool#GenericObjectPool(org.apache.commons.pool.PoolableObjectFactory,
1782 * org.apache.commons.pool.impl.GenericObjectPool.Config)
1783 * @see GenericObjectPool#setConfig
1784 */
1785 public static class Config {
1786 //CHECKSTYLE: stop VisibilityModifier
1787 /**
1788 * @see GenericObjectPool#setMaxIdle
1789 */
1790 public int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE;
1791 /**
1792 * @see GenericObjectPool#setMinIdle
1793 */
1794 public int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE;
1795 /**
1796 * @see GenericObjectPool#setMaxActive
1797 */
1798 public int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE;
1799 /**
1800 * @see GenericObjectPool#setMaxWait
1801 */
1802 public long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT;
1803 /**
1804 * @see GenericObjectPool#setWhenExhaustedAction
1805 */
1806 public byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
1807 /**
1808 * @see GenericObjectPool#setTestOnBorrow
1809 */
1810 public boolean testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
1811 /**
1812 * @see GenericObjectPool#setTestOnReturn
1813 */
1814 public boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
1815 /**
1816 * @see GenericObjectPool#setTestWhileIdle
1817 */
1818 public boolean testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
1819 /**
1820 * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis
1821 */
1822 public long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
1823 /**
1824 * @see GenericObjectPool#setNumTestsPerEvictionRun
1825 */
1826 public int numTestsPerEvictionRun = GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
1827 /**
1828 * @see GenericObjectPool#setMinEvictableIdleTimeMillis
1829 */
1830 public long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1831 /**
1832 * @see GenericObjectPool#setSoftMinEvictableIdleTimeMillis
1833 */
1834 public long softMinEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1835 /**
1836 * @see GenericObjectPool#setLifo
1837 */
1838 public boolean lifo = GenericObjectPool.DEFAULT_LIFO;
1839 //CHECKSTYLE: resume VisibilityModifier
1840 }
1841
1842 /**
1843 * Latch used to control allocation order of objects to threads to ensure
1844 * fairness. That is, objects are allocated to threads in the order that
1845 * threads request objects.
1846 */
1847 private static final class Latch {
1848
1849 /** object timestamp pair allocated to this latch */
1850 private ObjectTimestampPair _pair;
1851
1852 /** Whether or not this latch may create an object instance */
1853 private boolean _mayCreate = false;
1854
1855 /**
1856 * Returns ObjectTimestampPair allocated to this latch
1857 * @return ObjectTimestampPair allocated to this latch
1858 */
1859 private synchronized ObjectTimestampPair getPair() {
1860 return _pair;
1861 }
1862
1863 /**
1864 * Sets ObjectTimestampPair on this latch
1865 * @param pair ObjectTimestampPair allocated to this latch
1866 */
1867 private synchronized void setPair(ObjectTimestampPair pair) {
1868 _pair = pair;
1869 }
1870
1871 /**
1872 * Whether or not this latch may create an object instance
1873 * @return true if this latch has an instance creation permit
1874 */
1875 private synchronized boolean mayCreate() {
1876 return _mayCreate;
1877 }
1878
1879 /**
1880 * Sets the mayCreate property
1881 * @param mayCreate new value for mayCreate
1882 */
1883 private synchronized void setMayCreate(boolean mayCreate) {
1884 _mayCreate = mayCreate;
1885 }
1886
1887 /**
1888 * Reset the latch data. Used when an allocation fails and the latch
1889 * needs to be re-added to the queue.
1890 */
1891 private synchronized void reset() {
1892 _pair = null;
1893 _mayCreate = false;
1894 }
1895 }
1896
1897
1898 //--- private attributes ---------------------------------------
1899
1900 /**
1901 * The cap on the number of idle instances in the pool.
1902 * @see #setMaxIdle
1903 * @see #getMaxIdle
1904 */
1905 private int _maxIdle = DEFAULT_MAX_IDLE;
1906
1907 /**
1908 * The cap on the minimum number of idle instances in the pool.
1909 * @see #setMinIdle
1910 * @see #getMinIdle
1911 */
1912 private int _minIdle = DEFAULT_MIN_IDLE;
1913
1914 /**
1915 * The cap on the total number of active instances from the pool.
1916 * @see #setMaxActive
1917 * @see #getMaxActive
1918 */
1919 private int _maxActive = DEFAULT_MAX_ACTIVE;
1920
1921 /**
1922 * The maximum amount of time (in millis) the
1923 * {@link #borrowObject} method should block before throwing
1924 * an exception when the pool is exhausted and the
1925 * {@link #getWhenExhaustedAction "when exhausted" action} is
1926 * {@link #WHEN_EXHAUSTED_BLOCK}.
1927 *
1928 * When less than or equal to 0, the {@link #borrowObject} method
1929 * may block indefinitely.
1930 *
1931 * @see #setMaxWait
1932 * @see #getMaxWait
1933 * @see #WHEN_EXHAUSTED_BLOCK
1934 * @see #setWhenExhaustedAction
1935 * @see #getWhenExhaustedAction
1936 */
1937 private long _maxWait = DEFAULT_MAX_WAIT;
1938
1939 /**
1940 * The action to take when the {@link #borrowObject} method
1941 * is invoked when the pool is exhausted (the maximum number
1942 * of "active" objects has been reached).
1943 *
1944 * @see #WHEN_EXHAUSTED_BLOCK
1945 * @see #WHEN_EXHAUSTED_FAIL
1946 * @see #WHEN_EXHAUSTED_GROW
1947 * @see #DEFAULT_WHEN_EXHAUSTED_ACTION
1948 * @see #setWhenExhaustedAction
1949 * @see #getWhenExhaustedAction
1950 */
1951 private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION;
1952
1953 /**
1954 * When <tt>true</tt>, objects will be
1955 * {@link PoolableObjectFactory#validateObject validated}
1956 * before being returned by the {@link #borrowObject}
1957 * method. If the object fails to validate,
1958 * it will be dropped from the pool, and we will attempt
1959 * to borrow another.
1960 *
1961 * @see #setTestOnBorrow
1962 * @see #getTestOnBorrow
1963 */
1964 private volatile boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW;
1965
1966 /**
1967 * When <tt>true</tt>, objects will be
1968 * {@link PoolableObjectFactory#validateObject validated}
1969 * before being returned to the pool within the
1970 * {@link #returnObject}.
1971 *
1972 * @see #getTestOnReturn
1973 * @see #setTestOnReturn
1974 */
1975 private volatile boolean _testOnReturn = DEFAULT_TEST_ON_RETURN;
1976
1977 /**
1978 * When <tt>true</tt>, objects will be
1979 * {@link PoolableObjectFactory#validateObject validated}
1980 * by the idle object evictor (if any). If an object
1981 * fails to validate, it will be dropped from the pool.
1982 *
1983 * @see #setTestWhileIdle
1984 * @see #getTestWhileIdle
1985 * @see #getTimeBetweenEvictionRunsMillis
1986 * @see #setTimeBetweenEvictionRunsMillis
1987 */
1988 private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE;
1989
1990 /**
1991 * The number of milliseconds to sleep between runs of the
1992 * idle object evictor thread.
1993 * When non-positive, no idle object evictor thread will be
1994 * run.
1995 *
1996 * @see #setTimeBetweenEvictionRunsMillis
1997 * @see #getTimeBetweenEvictionRunsMillis
1998 */
1999 private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
2000
2001 /**
2002 * The max number of objects to examine during each run of the
2003 * idle object evictor thread (if any).
2004 * <p>
2005 * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
2006 * tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
2007 * idle objects will be tested per run.
2008 *
2009 * @see #setNumTestsPerEvictionRun
2010 * @see #getNumTestsPerEvictionRun
2011 * @see #getTimeBetweenEvictionRunsMillis
2012 * @see #setTimeBetweenEvictionRunsMillis
2013 */
2014 private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
2015
2016 /**
2017 * The minimum amount of time an object may sit idle in the pool
2018 * before it is eligible for eviction by the idle object evictor
2019 * (if any).
2020 * When non-positive, no objects will be evicted from the pool
2021 * due to idle time alone.
2022 *
2023 * @see #setMinEvictableIdleTimeMillis
2024 * @see #getMinEvictableIdleTimeMillis
2025 * @see #getTimeBetweenEvictionRunsMillis
2026 * @see #setTimeBetweenEvictionRunsMillis
2027 */
2028 private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
2029
2030 /**
2031 * The minimum amount of time an object may sit idle in the pool
2032 * before it is eligible for eviction by the idle object evictor
2033 * (if any), with the extra condition that at least
2034 * "minIdle" amount of object remain in the pool.
2035 * When non-positive, no objects will be evicted from the pool
2036 * due to idle time alone.
2037 *
2038 * @see #setSoftMinEvictableIdleTimeMillis
2039 * @see #getSoftMinEvictableIdleTimeMillis
2040 */
2041 private long _softMinEvictableIdleTimeMillis = DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
2042
2043 /** Whether or not the pool behaves as a LIFO queue (last in first out) */
2044 private boolean _lifo = DEFAULT_LIFO;
2045
2046 /** My pool. */
2047 private CursorableLinkedList _pool = null;
2048
2049 /** Eviction cursor - keeps track of idle object evictor position */
2050 private CursorableLinkedList.Cursor _evictionCursor = null;
2051
2052 /** My {@link PoolableObjectFactory}. */
2053 private PoolableObjectFactory _factory = null;
2054
2055 /**
2056 * The number of objects {@link #borrowObject} borrowed
2057 * from the pool, but not yet returned.
2058 */
2059 private int _numActive = 0;
2060
2061 /**
2062 * My idle object eviction {@link TimerTask}, if any.
2063 */
2064 private Evictor _evictor = null;
2065
2066 /**
2067 * The number of objects subject to some form of internal processing
2068 * (usually creation or destruction) that should be included in the total
2069 * number of objects but are neither active nor idle.
2070 */
2071 private int _numInternalProcessing = 0;
2072
2073 /**
2074 * Used to track the order in which threads call {@link #borrowObject()} so
2075 * that objects can be allocated in the order in which the threads requested
2076 * them.
2077 */
2078 private final LinkedList _allocationQueue = new LinkedList();
2079
2080 }