1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.pool.impl;
19
20 import java.util.Iterator;
21 import java.util.NoSuchElementException;
22 import java.util.TimerTask;
23
24 import org.apache.commons.pool.BaseObjectPool;
25 import org.apache.commons.pool.ObjectPool;
26 import org.apache.commons.pool.PoolableObjectFactory;
27 import org.apache.commons.pool.impl.GenericKeyedObjectPool.ObjectTimestampPair;
28
29 /***
30 * A configurable {@link ObjectPool} implementation.
31 * <p>
32 * When coupled with the appropriate {@link PoolableObjectFactory},
33 * <tt>GenericObjectPool</tt> provides robust pooling functionality for
34 * arbitrary objects.
35 * <p>
36 * A <tt>GenericObjectPool</tt> provides a number of configurable parameters:
37 * <ul>
38 * <li>
39 * {@link #setMaxActive <i>maxActive</i>} controls the maximum number of
40 * objects that can be borrowed from the pool at one time. When
41 * non-positive, there is no limit to the number of objects that may be
42 * active at one time. When {@link #setMaxActive <i>maxActive</i>} is
43 * exceeded, the pool is said to be exhausted. The default setting for this
44 * parameter is 8.
45 * </li>
46 * <li>
47 * {@link #setMaxIdle <i>maxIdle</i>} controls the maximum number of objects
48 * that can sit idle in the pool at any time. When negative, there is no
49 * limit to the number of objects that may be idle at one time. The default
50 * setting for this parameter is 8.
51 * </li>
52 * <li>
53 * {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} specifies the
54 * behavior of the {@link #borrowObject} method when the pool is exhausted:
55 * <ul>
56 * <li>
57 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
58 * {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject} will throw
59 * a {@link NoSuchElementException}
60 * </li>
61 * <li>
62 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
63 * {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject} will create a new
64 * object and return it(essentially making {@link #setMaxActive <i>maxActive</i>}
65 * meaningless.)
66 * </li>
67 * <li>
68 * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>}
69 * is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject} will block
70 * (invoke {@link Object#wait()} until a new or idle object is available.
71 * If a positive {@link #setMaxWait <i>maxWait</i>}
72 * value is supplied, the {@link #borrowObject} will block for at
73 * most that many milliseconds, after which a {@link NoSuchElementException}
74 * will be thrown. If {@link #setMaxWait <i>maxWait</i>} is non-positive,
75 * the {@link #borrowObject} method will block indefinitely.
76 * </li>
77 * </ul>
78 * The default <code>whenExhaustedAction</code> setting is
79 * {@link #WHEN_EXHAUSTED_BLOCK} and the default <code>maxWait</code>
80 * setting is -1. By default, therefore, <code>borrowObject</code> will
81 * block indefinitely until an idle instance becomes available.
82 * </li>
83 * <li>
84 * When {@link #setTestOnBorrow <i>testOnBorrow</i>} is set, the pool will
85 * attempt to validate each object before it is returned from the
86 * {@link #borrowObject} method. (Using the provided factory's
87 * {@link PoolableObjectFactory#validateObject} method.) Objects that fail
88 * to validate will be dropped from the pool, and a different object will
89 * be borrowed. The default setting for this parameter is
90 * <code>false.</code>
91 * </li>
92 * <li>
93 * When {@link #setTestOnReturn <i>testOnReturn</i>} is set, the pool will
94 * attempt to validate each object before it is returned to the pool in the
95 * {@link #returnObject} method. (Using the provided factory's
96 * {@link PoolableObjectFactory#validateObject}
97 * method.) Objects that fail to validate will be dropped from the pool.
98 * The default setting for this parameter is <code>false.</code>
99 * </li>
100 * </ul>
101 * <p>
102 * Optionally, one may configure the pool to examine and possibly evict objects
103 * as they sit idle in the pool and to ensure that a minimum number of idle
104 * objects are available. This is performed by an "idle object eviction"
105 * thread, which runs asynchronously. Caution should be used when configuring
106 * this optional feature. Eviction runs require an exclusive synchronization
107 * lock on the pool, so if they run too frequently and / or incur excessive
108 * latency when creating, destroying or validating object instances,
109 * performance issues may result. The idle object eviction thread may be
110 * configured using the following attributes:
111 * <ul>
112 * <li>
113 * {@link #setTimeBetweenEvictionRunsMillis <i>timeBetweenEvictionRunsMillis</i>}
114 * indicates how long the eviction thread should sleep before "runs" of examining
115 * idle objects. When non-positive, no eviction thread will be launched. The
116 * default setting for this parameter is -1 (i.e., idle object eviction is
117 * disabled by default).
118 * </li>
119 * <li>
120 * {@link #setMinEvictableIdleTimeMillis <i>minEvictableIdleTimeMillis</i>}
121 * specifies the minimum amount of time that an object may sit idle in the pool
122 * before it is eligible for eviction due to idle time. When non-positive, no object
123 * will be dropped from the pool due to idle time alone. This setting has no
124 * effect unless <code>timeBetweenEvictionRunsMillis > 0.</code> The default
125 * setting for this parameter is 30 minutes.
126 * </li>
127 * <li>
128 * {@link #setTestWhileIdle <i>testWhileIdle</i>} indicates whether or not idle
129 * objects should be validated using the factory's
130 * {@link PoolableObjectFactory#validateObject} method. Objects that fail to
131 * validate will be dropped from the pool. This setting has no effect unless
132 * <code>timeBetweenEvictionRunsMillis > 0.</code> The default setting for
133 * this parameter is <code>false.</code>
134 * </li>
135 * <li>
136 * {@link #setSoftMinEvictableIdleTimeMillis <i>softMinEvictableIdleTimeMillis</i>}
137 * specifies the minimum amount of time an object may sit idle in the pool
138 * before it is eligible for eviction by the idle object evictor
139 * (if any), with the extra condition that at least "minIdle" amount of object
140 * remain in the pool. When non-positive, no objects will be evicted from the pool
141 * due to idle time alone. This setting has no effect unless
142 * <code>timeBetweenEvictionRunsMillis > 0.</code> The default setting for
143 * this parameter is -1 (disabled).
144 * </li>
145 * <li>
146 * {@link #setNumTestsPerEvictionRun <i>numTestsPerEvictionRun</i>}
147 * determines the number of objects examined in each run of the idle object
148 * evictor. This setting has no effect unless
149 * <code>timeBetweenEvictionRunsMillis > 0.</code> The default setting for
150 * this parameter is 3.
151 * </li>
152 * </ul>
153 * <p>
154 * <p>
155 * The pool can be configured to behave as a LIFO queue with respect to idle
156 * objects - always returning the most recently used object from the pool,
157 * or as a FIFO queue, where borrowObject always returns the oldest object
158 * in the idle object pool.
159 * <ul>
160 * <li>
161 * {@link #setLifo <i>lifo</i>}
162 * determines whether or not the pool returns idle objects in
163 * last-in-first-out order. The default setting for this parameter is
164 * <code>true.</code>
165 * </li>
166 * </ul>
167 * <p>
168 * GenericObjectPool is not usable without a {@link PoolableObjectFactory}. A
169 * non-<code>null</code> factory must be provided either as a constructor argument
170 * or via a call to {@link #setFactory} before the pool is used.
171 *
172 * @see GenericKeyedObjectPool
173 * @author Rodney Waldhoff
174 * @author Dirk Verbeeck
175 * @author Sandy McArthur
176 * @version $Revision: 609487 $ $Date: 2008-01-06 19:36:42 -0700 (Sun, 06 Jan 2008) $
177 * @since Pool 1.0
178 */
179 public class GenericObjectPool extends BaseObjectPool implements ObjectPool {
180
181
182
183 /***
184 * A "when exhausted action" type indicating that when the pool is
185 * exhausted (i.e., the maximum number of active objects has
186 * been reached), the {@link #borrowObject}
187 * method should fail, throwing a {@link NoSuchElementException}.
188 * @see #WHEN_EXHAUSTED_BLOCK
189 * @see #WHEN_EXHAUSTED_GROW
190 * @see #setWhenExhaustedAction
191 */
192 public static final byte WHEN_EXHAUSTED_FAIL = 0;
193
194 /***
195 * A "when exhausted action" type indicating that when the pool
196 * is exhausted (i.e., the maximum number
197 * of active objects has been reached), the {@link #borrowObject}
198 * method should block until a new object is available, or the
199 * {@link #getMaxWait maximum wait time} has been reached.
200 * @see #WHEN_EXHAUSTED_FAIL
201 * @see #WHEN_EXHAUSTED_GROW
202 * @see #setMaxWait
203 * @see #getMaxWait
204 * @see #setWhenExhaustedAction
205 */
206 public static final byte WHEN_EXHAUSTED_BLOCK = 1;
207
208 /***
209 * A "when exhausted action" type indicating that when the pool is
210 * exhausted (i.e., the maximum number
211 * of active objects has been reached), the {@link #borrowObject}
212 * method should simply create a new object anyway.
213 * @see #WHEN_EXHAUSTED_FAIL
214 * @see #WHEN_EXHAUSTED_GROW
215 * @see #setWhenExhaustedAction
216 */
217 public static final byte WHEN_EXHAUSTED_GROW = 2;
218
219 /***
220 * The default cap on the number of "sleeping" instances in the pool.
221 * @see #getMaxIdle
222 * @see #setMaxIdle
223 */
224 public static final int DEFAULT_MAX_IDLE = 8;
225
226 /***
227 * The default minimum number of "sleeping" instances in the pool
228 * before before the evictor thread (if active) spawns new objects.
229 * @see #getMinIdle
230 * @see #setMinIdle
231 */
232 public static final int DEFAULT_MIN_IDLE = 0;
233
234 /***
235 * The default cap on the total number of active instances from the pool.
236 * @see #getMaxActive
237 */
238 public static final int DEFAULT_MAX_ACTIVE = 8;
239
240 /***
241 * The default "when exhausted action" for the pool.
242 * @see #WHEN_EXHAUSTED_BLOCK
243 * @see #WHEN_EXHAUSTED_FAIL
244 * @see #WHEN_EXHAUSTED_GROW
245 * @see #setWhenExhaustedAction
246 */
247 public static final byte DEFAULT_WHEN_EXHAUSTED_ACTION = WHEN_EXHAUSTED_BLOCK;
248
249 /***
250 * The default LIFO status. True means that borrowObject returns the
251 * most recently used ("last in") idle object in the pool (if there are
252 * idle instances available). False means that the pool behaves as a FIFO
253 * queue - objects are taken from the idle object pool in the order that
254 * they are returned to the pool.
255 * @see #setLifo
256 * @since 1.4
257 */
258 public static final boolean DEFAULT_LIFO = true;
259
260 /***
261 * The default maximum amount of time (in milliseconds) the
262 * {@link #borrowObject} method should block before throwing
263 * an exception when the pool is exhausted and the
264 * {@link #getWhenExhaustedAction "when exhausted" action} is
265 * {@link #WHEN_EXHAUSTED_BLOCK}.
266 * @see #getMaxWait
267 * @see #setMaxWait
268 */
269 public static final long DEFAULT_MAX_WAIT = -1L;
270
271 /***
272 * The default "test on borrow" value.
273 * @see #getTestOnBorrow
274 * @see #setTestOnBorrow
275 */
276 public static final boolean DEFAULT_TEST_ON_BORROW = false;
277
278 /***
279 * The default "test on return" value.
280 * @see #getTestOnReturn
281 * @see #setTestOnReturn
282 */
283 public static final boolean DEFAULT_TEST_ON_RETURN = false;
284
285 /***
286 * The default "test while idle" value.
287 * @see #getTestWhileIdle
288 * @see #setTestWhileIdle
289 * @see #getTimeBetweenEvictionRunsMillis
290 * @see #setTimeBetweenEvictionRunsMillis
291 */
292 public static final boolean DEFAULT_TEST_WHILE_IDLE = false;
293
294 /***
295 * The default "time between eviction runs" value.
296 * @see #getTimeBetweenEvictionRunsMillis
297 * @see #setTimeBetweenEvictionRunsMillis
298 */
299 public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L;
300
301 /***
302 * The default number of objects to examine per run in the
303 * idle object evictor.
304 * @see #getNumTestsPerEvictionRun
305 * @see #setNumTestsPerEvictionRun
306 * @see #getTimeBetweenEvictionRunsMillis
307 * @see #setTimeBetweenEvictionRunsMillis
308 */
309 public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3;
310
311 /***
312 * The default value for {@link #getMinEvictableIdleTimeMillis}.
313 * @see #getMinEvictableIdleTimeMillis
314 * @see #setMinEvictableIdleTimeMillis
315 */
316 public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L;
317
318 /***
319 * The default value for {@link #getSoftMinEvictableIdleTimeMillis}.
320 * @see #getSoftMinEvictableIdleTimeMillis
321 * @see #setSoftMinEvictableIdleTimeMillis
322 */
323 public static final long DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = -1;
324
325
326
327 /***
328 * Create a new <tt>GenericObjectPool</tt>.
329 */
330 public GenericObjectPool() {
331 this(null,DEFAULT_MAX_ACTIVE,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
332 }
333
334 /***
335 * Create a new <tt>GenericObjectPool</tt> using the specified values.
336 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
337 */
338 public GenericObjectPool(PoolableObjectFactory factory) {
339 this(factory,DEFAULT_MAX_ACTIVE,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
340 }
341
342 /***
343 * Create a new <tt>GenericObjectPool</tt> using the specified values.
344 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
345 * @param config a non-<tt>null</tt> {@link GenericObjectPool.Config} describing my configuration
346 */
347 public GenericObjectPool(PoolableObjectFactory factory, GenericObjectPool.Config config) {
348 this(factory,config.maxActive,config.whenExhaustedAction,config.maxWait,config.maxIdle,config.minIdle,config.testOnBorrow,config.testOnReturn,config.timeBetweenEvictionRunsMillis,config.numTestsPerEvictionRun,config.minEvictableIdleTimeMillis,config.testWhileIdle,config.softMinEvictableIdleTimeMillis, config.lifo);
349 }
350
351 /***
352 * Create a new <tt>GenericObjectPool</tt> using the specified values.
353 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
354 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
355 */
356 public GenericObjectPool(PoolableObjectFactory factory, int maxActive) {
357 this(factory,maxActive,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
358 }
359
360 /***
361 * Create a new <tt>GenericObjectPool</tt> using the specified values.
362 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
363 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
364 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
365 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
366 */
367 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait) {
368 this(factory,maxActive,whenExhaustedAction,maxWait,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
369 }
370
371 /***
372 * Create a new <tt>GenericObjectPool</tt> using the specified values.
373 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
374 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
375 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
376 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
377 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #getTestOnBorrow})
378 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #getTestOnReturn})
379 */
380 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, boolean testOnBorrow, boolean testOnReturn) {
381 this(factory,maxActive,whenExhaustedAction,maxWait,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,testOnBorrow,testOnReturn,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
382 }
383
384 /***
385 * Create a new <tt>GenericObjectPool</tt> using the specified values.
386 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
387 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
388 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
389 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
390 * @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle})
391 */
392 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle) {
393 this(factory,maxActive,whenExhaustedAction,maxWait,maxIdle,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
394 }
395
396 /***
397 * Create a new <tt>GenericObjectPool</tt> using the specified values.
398 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
399 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
400 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
401 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
402 * @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle})
403 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #getTestOnBorrow})
404 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #getTestOnReturn})
405 */
406 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn) {
407 this(factory,maxActive,whenExhaustedAction,maxWait,maxIdle,DEFAULT_MIN_IDLE,testOnBorrow,testOnReturn,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
408 }
409
410 /***
411 * Create a new <tt>GenericObjectPool</tt> using the specified values.
412 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
413 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
414 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
415 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
416 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
417 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
418 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
419 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
420 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
421 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis})
422 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
423 */
424 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) {
425 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle);
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 from me at one time (see {@link #setMaxActive})
432 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
433 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
434 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
435 * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle})
436 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
437 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
438 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
439 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
440 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis})
441 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
442 */
443 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, int minIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) {
444 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, minIdle, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle, DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
445 }
446
447 /***
448 * Create a new <tt>GenericObjectPool</tt> using the specified values.
449 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
450 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
451 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
452 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
453 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
454 * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle})
455 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
456 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
457 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
458 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
459 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis})
460 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
461 * @param softMinEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligible for eviction with the extra condition that at least "minIdle" amount of object remain in the pool. (see {@link #setSoftMinEvictableIdleTimeMillis})
462 * @since Pool 1.3
463 */
464 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, int minIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle, long softMinEvictableIdleTimeMillis) {
465 this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, minIdle, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle, softMinEvictableIdleTimeMillis, DEFAULT_LIFO);
466 }
467
468 /***
469 * Create a new <tt>GenericObjectPool</tt> using the specified values.
470 * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
471 * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
472 * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
473 * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
474 * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
475 * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle})
476 * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
477 * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
478 * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
479 * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
480 * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis})
481 * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
482 * @param softMinEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligible for eviction with the extra condition that at least "minIdle" amount of object remain in the pool. (see {@link #setSoftMinEvictableIdleTimeMillis})
483 * @param lifo whether or not objects are returned in last-in-first-out order from the idle object pool (see {@link #setLifo})
484 * @since Pool 1.4
485 */
486 public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, int minIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle, long softMinEvictableIdleTimeMillis, boolean lifo) {
487 _factory = factory;
488 _maxActive = maxActive;
489 _lifo = lifo;
490 switch(whenExhaustedAction) {
491 case WHEN_EXHAUSTED_BLOCK:
492 case WHEN_EXHAUSTED_FAIL:
493 case WHEN_EXHAUSTED_GROW:
494 _whenExhaustedAction = whenExhaustedAction;
495 break;
496 default:
497 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
498 }
499 _maxWait = maxWait;
500 _maxIdle = maxIdle;
501 _minIdle = minIdle;
502 _testOnBorrow = testOnBorrow;
503 _testOnReturn = testOnReturn;
504 _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
505 _numTestsPerEvictionRun = numTestsPerEvictionRun;
506 _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
507 _softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
508 _testWhileIdle = testWhileIdle;
509
510 _pool = new CursorableLinkedList();
511 startEvictor(_timeBetweenEvictionRunsMillis);
512 }
513
514
515
516
517
518 /***
519 * Returns the cap on the total number of active instances from the pool.
520 * @return the cap on the total number of active instances from the pool.
521 * @see #setMaxActive
522 */
523 public synchronized int getMaxActive() {
524 return _maxActive;
525 }
526
527 /***
528 * Sets the cap on the total number of active instances from the pool.
529 * @param maxActive The cap on the total number of active instances from the pool.
530 * Use a negative value for no limit.
531 * @see #getMaxActive
532 */
533 public synchronized void setMaxActive(int maxActive) {
534 _maxActive = maxActive;
535 notifyAll();
536 }
537
538 /***
539 * Returns the action to take when the {@link #borrowObject} method
540 * is invoked when the pool is exhausted (the maximum number
541 * of "active" objects has been reached).
542 *
543 * @return one of {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW}
544 * @see #setWhenExhaustedAction
545 */
546 public synchronized byte getWhenExhaustedAction() {
547 return _whenExhaustedAction;
548 }
549
550 /***
551 * Sets the action to take when the {@link #borrowObject} method
552 * is invoked when the pool is exhausted (the maximum number
553 * of "active" objects has been reached).
554 *
555 * @param whenExhaustedAction the action code, which must be one of
556 * {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL},
557 * or {@link #WHEN_EXHAUSTED_GROW}
558 * @see #getWhenExhaustedAction
559 */
560 public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) {
561 switch(whenExhaustedAction) {
562 case WHEN_EXHAUSTED_BLOCK:
563 case WHEN_EXHAUSTED_FAIL:
564 case WHEN_EXHAUSTED_GROW:
565 _whenExhaustedAction = whenExhaustedAction;
566 notifyAll();
567 break;
568 default:
569 throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
570 }
571 }
572
573
574 /***
575 * Returns the maximum amount of time (in milliseconds) the
576 * {@link #borrowObject} method should block before throwing
577 * an exception when the pool is exhausted and the
578 * {@link #setWhenExhaustedAction "when exhausted" action} is
579 * {@link #WHEN_EXHAUSTED_BLOCK}.
580 *
581 * When less than or equal to 0, the {@link #borrowObject} method
582 * may block indefinitely.
583 *
584 * @return maximum number of milliseconds to block when borrowing an object.
585 * @see #setMaxWait
586 * @see #setWhenExhaustedAction
587 * @see #WHEN_EXHAUSTED_BLOCK
588 */
589 public synchronized long getMaxWait() {
590 return _maxWait;
591 }
592
593 /***
594 * Sets the maximum amount of time (in milliseconds) the
595 * {@link #borrowObject} method should block before throwing
596 * an exception when the pool is exhausted and the
597 * {@link #setWhenExhaustedAction "when exhausted" action} is
598 * {@link #WHEN_EXHAUSTED_BLOCK}.
599 *
600 * When less than or equal to 0, the {@link #borrowObject} method
601 * may block indefinitely.
602 *
603 * @param maxWait maximum number of milliseconds to block when borrowing an object.
604 * @see #getMaxWait
605 * @see #setWhenExhaustedAction
606 * @see #WHEN_EXHAUSTED_BLOCK
607 */
608 public synchronized void setMaxWait(long maxWait) {
609 _maxWait = maxWait;
610 notifyAll();
611 }
612
613 /***
614 * Returns the cap on the number of "idle" instances in the pool.
615 * @return the cap on the number of "idle" instances in the pool.
616 * @see #setMaxIdle
617 */
618 public synchronized int getMaxIdle() {
619 return _maxIdle;
620 }
621
622 /***
623 * Sets the cap on the number of "idle" instances in the pool.
624 * @param maxIdle The cap on the number of "idle" instances in the pool.
625 * Use a negative value to indicate an unlimited number of idle instances.
626 * @see #getMaxIdle
627 */
628 public synchronized void setMaxIdle(int maxIdle) {
629 _maxIdle = maxIdle;
630 notifyAll();
631 }
632
633 /***
634 * Sets the minimum number of objects allowed in the pool
635 * before the evictor thread (if active) spawns new objects.
636 * Note that no objects are created when
637 * <code>numActive + numIdle >= maxActive.</code>
638 * This setting has no effect if the idle object evictor is disabled
639 * (i.e. if <code>timeBetweenEvictionRunsMillis <= 0</code>).
640 *
641 * @param minIdle The minimum number of objects.
642 * @see #getMinIdle
643 * @see #getTimeBetweenEvictionRunsMillis()
644 */
645 public synchronized void setMinIdle(int minIdle) {
646 _minIdle = minIdle;
647 notifyAll();
648 }
649
650 /***
651 * Returns the minimum number of objects allowed in the pool
652 * before the evictor thread (if active) spawns new objects.
653 * (Note no objects are created when: numActive + numIdle >= maxActive)
654 *
655 * @return The minimum number of objects.
656 * @see #setMinIdle
657 */
658 public synchronized int getMinIdle() {
659 return _minIdle;
660 }
661
662 /***
663 * When <tt>true</tt>, objects will be
664 * {@link PoolableObjectFactory#validateObject validated}
665 * before being returned by the {@link #borrowObject}
666 * method. If the object fails to validate,
667 * it will be dropped from the pool, and we will attempt
668 * to borrow another.
669 *
670 * @return <code>true</code> if objects are validated before being borrowed.
671 * @see #setTestOnBorrow
672 */
673 public boolean getTestOnBorrow() {
674 return _testOnBorrow;
675 }
676
677 /***
678 * When <tt>true</tt>, objects will be
679 * {@link PoolableObjectFactory#validateObject validated}
680 * before being returned by the {@link #borrowObject}
681 * method. If the object fails to validate,
682 * it will be dropped from the pool, and we will attempt
683 * to borrow another.
684 *
685 * @param testOnBorrow <code>true</code> if objects should be validated before being borrowed.
686 * @see #getTestOnBorrow
687 */
688 public void setTestOnBorrow(boolean testOnBorrow) {
689 _testOnBorrow = testOnBorrow;
690 }
691
692 /***
693 * When <tt>true</tt>, objects will be
694 * {@link PoolableObjectFactory#validateObject validated}
695 * before being returned to the pool within the
696 * {@link #returnObject}.
697 *
698 * @return <code>true</code> when objects will be validated after returned to {@link #returnObject}.
699 * @see #setTestOnReturn
700 */
701 public boolean getTestOnReturn() {
702 return _testOnReturn;
703 }
704
705 /***
706 * When <tt>true</tt>, objects will be
707 * {@link PoolableObjectFactory#validateObject validated}
708 * before being returned to the pool within the
709 * {@link #returnObject}.
710 *
711 * @param testOnReturn <code>true</code> so objects will be validated after returned to {@link #returnObject}.
712 * @see #getTestOnReturn
713 */
714 public void setTestOnReturn(boolean testOnReturn) {
715 _testOnReturn = testOnReturn;
716 }
717
718 /***
719 * Returns the number of milliseconds to sleep between runs of the
720 * idle object evictor thread.
721 * When non-positive, no idle object evictor thread will be
722 * run.
723 *
724 * @return number of milliseconds to sleep between evictor runs.
725 * @see #setTimeBetweenEvictionRunsMillis
726 */
727 public synchronized long getTimeBetweenEvictionRunsMillis() {
728 return _timeBetweenEvictionRunsMillis;
729 }
730
731 /***
732 * Sets the number of milliseconds to sleep between runs of the
733 * idle object evictor thread.
734 * When non-positive, no idle object evictor thread will be
735 * run.
736 *
737 * @param timeBetweenEvictionRunsMillis number of milliseconds to sleep between evictor runs.
738 * @see #getTimeBetweenEvictionRunsMillis
739 */
740 public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
741 _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
742 startEvictor(_timeBetweenEvictionRunsMillis);
743 }
744
745 /***
746 * Returns the max number of objects to examine during each run of the
747 * idle object evictor thread (if any).
748 *
749 * @return max number of objects to examine during each evictor run.
750 * @see #setNumTestsPerEvictionRun
751 * @see #setTimeBetweenEvictionRunsMillis
752 */
753 public synchronized int getNumTestsPerEvictionRun() {
754 return _numTestsPerEvictionRun;
755 }
756
757 /***
758 * Sets the max number of objects to examine during each run of the
759 * idle object evictor thread (if any).
760 * <p>
761 * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
762 * tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
763 * idle objects will be tested per run.
764 *
765 * @param numTestsPerEvictionRun max number of objects to examine during each evictor run.
766 * @see #getNumTestsPerEvictionRun
767 * @see #setTimeBetweenEvictionRunsMillis
768 */
769 public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
770 _numTestsPerEvictionRun = numTestsPerEvictionRun;
771 }
772
773 /***
774 * Returns the minimum amount of time an object may sit idle in the pool
775 * before it is eligible for eviction by the idle object evictor
776 * (if any).
777 *
778 * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction.
779 * @see #setMinEvictableIdleTimeMillis
780 * @see #setTimeBetweenEvictionRunsMillis
781 */
782 public synchronized long getMinEvictableIdleTimeMillis() {
783 return _minEvictableIdleTimeMillis;
784 }
785
786 /***
787 * Sets the minimum amount of time an object may sit idle in the pool
788 * before it is eligible for eviction by the idle object evictor
789 * (if any).
790 * When non-positive, no objects will be evicted from the pool
791 * due to idle time alone.
792 * @param minEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before it is eligible for eviction.
793 * @see #getMinEvictableIdleTimeMillis
794 * @see #setTimeBetweenEvictionRunsMillis
795 */
796 public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
797 _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
798 }
799
800 /***
801 * Returns the minimum amount of time an object may sit idle in the pool
802 * before it is eligible for eviction by the idle object evictor
803 * (if any), with the extra condition that at least
804 * "minIdle" amount of object remain in the pool.
805 *
806 * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction.
807 * @since Pool 1.3
808 * @see #setSoftMinEvictableIdleTimeMillis
809 */
810 public synchronized long getSoftMinEvictableIdleTimeMillis() {
811 return _softMinEvictableIdleTimeMillis;
812 }
813
814 /***
815 * Sets the minimum amount of time an object may sit idle in the pool
816 * before it is eligible for eviction by the idle object evictor
817 * (if any), with the extra condition that at least
818 * "minIdle" amount of object remain in the pool.
819 * When non-positive, no objects will be evicted from the pool
820 * due to idle time alone.
821 *
822 * @param softMinEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before it is eligible for eviction.
823 * @since Pool 1.3
824 * @see #getSoftMinEvictableIdleTimeMillis
825 */
826 public synchronized void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis) {
827 _softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
828 }
829
830 /***
831 * When <tt>true</tt>, objects will be
832 * {@link PoolableObjectFactory#validateObject validated}
833 * by the idle object evictor (if any). If an object
834 * fails to validate, it will be dropped from the pool.
835 *
836 * @return <code>true</code> when objects will be validated by the evictor.
837 * @see #setTestWhileIdle
838 * @see #setTimeBetweenEvictionRunsMillis
839 */
840 public synchronized boolean getTestWhileIdle() {
841 return _testWhileIdle;
842 }
843
844 /***
845 * When <tt>true</tt>, objects will be
846 * {@link PoolableObjectFactory#validateObject validated}
847 * by the idle object evictor (if any). If an object
848 * fails to validate, it will be dropped from the pool.
849 *
850 * @param testWhileIdle <code>true</code> so objects will be validated by the evictor.
851 * @see #getTestWhileIdle
852 * @see #setTimeBetweenEvictionRunsMillis
853 */
854 public synchronized void setTestWhileIdle(boolean testWhileIdle) {
855 _testWhileIdle = testWhileIdle;
856 }
857
858 /***
859 * Whether or not the idle object pool acts as a LIFO queue. True means
860 * that borrowObject returns the most recently used ("last in") idle object
861 * in the pool (if there are idle instances available). False means that
862 * the pool behaves as a FIFO queue - objects are taken from the idle object
863 * pool in the order that they are returned to the pool.
864 *
865 * @return <code>true</true> if the pool is configured to act as a LIFO queue
866 * @since 1.4
867 */
868 public synchronized boolean getLifo() {
869 return _lifo;
870 }
871
872 /***
873 * Sets the LIFO property of the pool. True means that borrowObject returns
874 * the most recently used ("last in") idle object in the pool (if there are
875 * idle instances available). False means that the pool behaves as a FIFO
876 * queue - objects are taken from the idle object pool in the order that
877 * they are returned to the pool.
878 *
879 * @param lifo the new value for the LIFO property
880 * @since 1.4
881 */
882 public synchronized void setLifo(boolean lifo) {
883 this._lifo = lifo;
884 }
885
886 /***
887 * Sets my configuration.
888 *
889 * @param conf configuration to use.
890 * @see GenericObjectPool.Config
891 */
892 public synchronized void setConfig(GenericObjectPool.Config conf) {
893 setMaxIdle(conf.maxIdle);
894 setMinIdle(conf.minIdle);
895 setMaxActive(conf.maxActive);
896 setMaxWait(conf.maxWait);
897 setWhenExhaustedAction(conf.whenExhaustedAction);
898 setTestOnBorrow(conf.testOnBorrow);
899 setTestOnReturn(conf.testOnReturn);
900 setTestWhileIdle(conf.testWhileIdle);
901 setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun);
902 setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
903 setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
904 setSoftMinEvictableIdleTimeMillis(conf.softMinEvictableIdleTimeMillis);
905 setLifo(conf.lifo);
906 notifyAll();
907 }
908
909
910
911 public Object borrowObject() throws Exception {
912 long starttime = System.currentTimeMillis();
913 for(;;) {
914 ObjectTimestampPair pair = null;
915
916 synchronized (this) {
917 assertOpen();
918
919 try {
920 pair = (ObjectTimestampPair)(_pool.removeFirst());
921 } catch(NoSuchElementException e) {
922 ;
923 }
924
925
926 if(null == pair) {
927
928
929 if(_maxActive < 0 || _numActive < _maxActive) {
930
931 } else {
932
933 switch(_whenExhaustedAction) {
934 case WHEN_EXHAUSTED_GROW:
935
936 break;
937 case WHEN_EXHAUSTED_FAIL:
938 throw new NoSuchElementException("Pool exhausted");
939 case WHEN_EXHAUSTED_BLOCK:
940 try {
941 if(_maxWait <= 0) {
942 wait();
943 } else {
944
945
946 final long elapsed = (System.currentTimeMillis() - starttime);
947 final long waitTime = _maxWait - elapsed;
948 if (waitTime > 0)
949 {
950 wait(waitTime);
951 }
952 }
953 } catch(InterruptedException e) {
954 Thread.currentThread().interrupt();
955 throw e;
956 }
957 if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
958 throw new NoSuchElementException("Timeout waiting for idle object");
959 } else {
960 continue;
961 }
962 default:
963 throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized.");
964 }
965 }
966 }
967 _numActive++;
968 }
969
970
971 boolean newlyCreated = false;
972 if(null == pair) {
973 try {
974 Object obj = _factory.makeObject();
975 pair = new ObjectTimestampPair(obj);
976 newlyCreated = true;
977 } finally {
978 if (!newlyCreated) {
979
980 synchronized (this) {
981 _numActive--;
982 notifyAll();
983 }
984 }
985 }
986 }
987
988
989 try {
990 _factory.activateObject(pair.value);
991 if(_testOnBorrow && !_factory.validateObject(pair.value)) {
992 throw new Exception("ValidateObject failed");
993 }
994 return pair.value;
995 }
996 catch (Throwable e) {
997
998 try {
999 _factory.destroyObject(pair.value);
1000 } catch (Throwable e2) {
1001
1002 }
1003 synchronized (this) {
1004 _numActive--;
1005 notifyAll();
1006 }
1007 if(newlyCreated) {
1008 throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
1009 }
1010 else {
1011 continue;
1012 }
1013 }
1014 }
1015 }
1016
1017 public void invalidateObject(Object obj) throws Exception {
1018 try {
1019 if (_factory != null) {
1020 _factory.destroyObject(obj);
1021 }
1022 } finally {
1023 synchronized (this) {
1024 _numActive--;
1025 notifyAll();
1026 }
1027 }
1028 }
1029
1030 /***
1031 * Clears any objects sitting idle in the pool.
1032 */
1033 public synchronized void clear() {
1034 for(Iterator it = _pool.iterator(); it.hasNext(); ) {
1035 try {
1036 _factory.destroyObject(((ObjectTimestampPair)(it.next())).value);
1037 } catch(Exception e) {
1038
1039 }
1040 it.remove();
1041 }
1042 _pool.clear();
1043 notifyAll();
1044 }
1045
1046 /***
1047 * Return the number of instances currently borrowed from this pool.
1048 *
1049 * @return the number of instances currently borrowed from this pool
1050 */
1051 public synchronized int getNumActive() {
1052 return _numActive;
1053 }
1054
1055 /***
1056 * Return the number of instances currently idle in this pool.
1057 *
1058 * @return the number of instances currently idle in this pool
1059 */
1060 public synchronized int getNumIdle() {
1061 return _pool.size();
1062 }
1063
1064 /***
1065 * {@inheritDoc}
1066 * <p><strong>Note: </strong> There is no guard to prevent an object
1067 * being returned to the pool multiple times. Clients are expected to
1068 * discard references to returned objects and ensure that an object is not
1069 * returned to the pool multiple times in sequence (i.e., without being
1070 * borrowed again between returns). Violating this contract will result in
1071 * the same object appearing multiple times in the pool and pool counters
1072 * (numActive, numIdle) returning incorrect values.</p>
1073 */
1074 public void returnObject(Object obj) throws Exception {
1075 try {
1076 addObjectToPool(obj, true);
1077 } catch (Exception e) {
1078 if (_factory != null) {
1079 try {
1080 _factory.destroyObject(obj);
1081 } catch (Exception e2) {
1082
1083 }
1084
1085
1086
1087 synchronized(this) {
1088 _numActive--;
1089 notifyAll();
1090 }
1091 }
1092 }
1093 }
1094
1095 private void addObjectToPool(Object obj, boolean decrementNumActive) throws Exception {
1096 boolean success = true;
1097 if(_testOnReturn && !(_factory.validateObject(obj))) {
1098 success = false;
1099 } else {
1100 _factory.passivateObject(obj);
1101 }
1102
1103 boolean shouldDestroy = !success;
1104
1105
1106
1107 synchronized (this) {
1108 if (isClosed()) {
1109 shouldDestroy = true;
1110 } else {
1111 if((_maxIdle >= 0) && (_pool.size() >= _maxIdle)) {
1112 shouldDestroy = true;
1113 } else if(success) {
1114
1115
1116 if (_lifo) {
1117 _pool.addFirst(new ObjectTimestampPair(obj));
1118 } else {
1119 _pool.addLast(new ObjectTimestampPair(obj));
1120 }
1121 }
1122 }
1123 }
1124
1125
1126 if(shouldDestroy) {
1127 try {
1128 _factory.destroyObject(obj);
1129 } catch(Exception e) {
1130
1131 }
1132 }
1133
1134
1135 if (decrementNumActive) {
1136 synchronized(this) {
1137 _numActive--;
1138 notifyAll();
1139 }
1140 }
1141 }
1142
1143 public void close() throws Exception {
1144 super.close();
1145 synchronized (this) {
1146 clear();
1147 startEvictor(-1L);
1148 }
1149 }
1150
1151 /***
1152 * Sets the {@link PoolableObjectFactory factory} this pool uses
1153 * to create new instances. Trying to change
1154 * the <code>factory</code> while there are borrowed objects will
1155 * throw an {@link IllegalStateException}.
1156 *
1157 * @param factory the {@link PoolableObjectFactory} used to create new instances.
1158 * @throws IllegalStateException when the factory cannot be set at this time
1159 */
1160 public synchronized void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
1161 assertOpen();
1162 if(0 < getNumActive()) {
1163 throw new IllegalStateException("Objects are already active");
1164 } else {
1165 clear();
1166 _factory = factory;
1167 }
1168 }
1169
1170 /***
1171 * <p>Perform <code>numTests</code> idle object eviction tests, evicting
1172 * examined objects that meet the criteria for eviction. If
1173 * <code>testWhileIdle</code> is true, examined objects are validated
1174 * when visited (and removed if invalid); otherwise only objects that
1175 * have been idle for more than <code>minEvicableIdletimeMillis</code>
1176 * are removed.</p>
1177 *
1178 * <p>Successive activations of this method examine objects in
1179 * in sequence, cycling through objects in oldest-to-youngest order.</p>
1180 *
1181 * @throws Exception if the pool is closed or eviction fails.
1182 */
1183 public synchronized void evict() throws Exception {
1184 assertOpen();
1185 if(!_pool.isEmpty()) {
1186 if (null == _evictionCursor) {
1187 _evictionCursor = (_pool.cursor(_lifo ? _pool.size() : 0));
1188 }
1189 for (int i=0,m=getNumTests();i<m;i++) {
1190 if ((_lifo && !_evictionCursor.hasPrevious()) ||
1191 !_lifo && !_evictionCursor.hasNext()) {
1192 _evictionCursor.close();
1193 _evictionCursor = _pool.cursor(_lifo ? _pool.size() : 0);
1194 }
1195 boolean removeObject = false;
1196 final ObjectTimestampPair pair = _lifo ?
1197 (ObjectTimestampPair) _evictionCursor.previous() :
1198 (ObjectTimestampPair) _evictionCursor.next();
1199 final long idleTimeMilis = System.currentTimeMillis() - pair.tstamp;
1200 if ((_minEvictableIdleTimeMillis > 0)
1201 && (idleTimeMilis > _minEvictableIdleTimeMillis)) {
1202 removeObject = true;
1203 } else if ((_softMinEvictableIdleTimeMillis > 0)
1204 && (idleTimeMilis > _softMinEvictableIdleTimeMillis)
1205 && (getNumIdle() > getMinIdle())) {
1206 removeObject = true;
1207 }
1208 if(_testWhileIdle && !removeObject) {
1209 boolean active = false;
1210 try {
1211 _factory.activateObject(pair.value);
1212 active = true;
1213 } catch(Exception e) {
1214 removeObject=true;
1215 }
1216 if(active) {
1217 if(!_factory.validateObject(pair.value)) {
1218 removeObject=true;
1219 } else {
1220 try {
1221 _factory.passivateObject(pair.value);
1222 } catch(Exception e) {
1223 removeObject=true;
1224 }
1225 }
1226 }
1227 }
1228 if(removeObject) {
1229 try {
1230 _evictionCursor.remove();
1231 _factory.destroyObject(pair.value);
1232 } catch(Exception e) {
1233
1234 }
1235 }
1236 }
1237 }
1238 }
1239
1240 /***
1241 * Check to see if we are below our minimum number of objects
1242 * if so enough to bring us back to our minimum.
1243 *
1244 * @throws Exception when {@link #addObject()} fails.
1245 */
1246 private void ensureMinIdle() throws Exception {
1247
1248
1249
1250
1251
1252 int objectDeficit = calculateDeficit();
1253 for ( int j = 0 ; j < objectDeficit && calculateDeficit() > 0 ; j++ ) {
1254 addObject();
1255 }
1256 }
1257
1258 private synchronized int calculateDeficit() {
1259 int objectDeficit = getMinIdle() - getNumIdle();
1260 if (_maxActive > 0) {
1261 int growLimit = Math.max(0, getMaxActive() - getNumActive() - getNumIdle());
1262 objectDeficit = Math.min(objectDeficit, growLimit);
1263 }
1264 return objectDeficit;
1265 }
1266
1267 /***
1268 * Create an object, and place it into the pool.
1269 * addObject() is useful for "pre-loading" a pool with idle objects.
1270 */
1271 public synchronized void addObject() throws Exception {
1272 assertOpen();
1273 if (_factory == null) {
1274 throw new IllegalStateException("Cannot add objects without a factory.");
1275 }
1276 Object obj = _factory.makeObject();
1277 try {
1278 assertOpen();
1279 addObjectToPool(obj, false);
1280 } catch (IllegalStateException ex) {
1281 try {
1282 _factory.destroyObject(obj);
1283 } catch (Exception ex2) {
1284
1285 }
1286 throw ex;
1287 }
1288 }
1289
1290
1291
1292 /***
1293 * Start the eviction thread or service, or when
1294 * <i>delay</i> is non-positive, stop it
1295 * if it is already running.
1296 *
1297 * @param delay milliseconds between evictor runs.
1298 */
1299 protected synchronized void startEvictor(long delay) {
1300 if(null != _evictor) {
1301 EvictionTimer.cancel(_evictor);
1302 _evictor = null;
1303 }
1304 if(delay > 0) {
1305 _evictor = new Evictor();
1306 EvictionTimer.schedule(_evictor, delay, delay);
1307 }
1308 }
1309
1310 synchronized String debugInfo() {
1311 StringBuffer buf = new StringBuffer();
1312 buf.append("Active: ").append(getNumActive()).append("\n");
1313 buf.append("Idle: ").append(getNumIdle()).append("\n");
1314 buf.append("Idle Objects:\n");
1315 Iterator it = _pool.iterator();
1316 long time = System.currentTimeMillis();
1317 while(it.hasNext()) {
1318 ObjectTimestampPair pair = (ObjectTimestampPair)(it.next());
1319 buf.append("\t").append(pair.value).append("\t").append(time - pair.tstamp).append("\n");
1320 }
1321 return buf.toString();
1322 }
1323
1324 private int getNumTests() {
1325 if(_numTestsPerEvictionRun >= 0) {
1326 return Math.min(_numTestsPerEvictionRun, _pool.size());
1327 } else {
1328 return(int)(Math.ceil((double)_pool.size()/Math.abs((double)_numTestsPerEvictionRun)));
1329 }
1330 }
1331
1332
1333
1334 /***
1335 * The idle object evictor {@link TimerTask}.
1336 * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis
1337 */
1338 private class Evictor extends TimerTask {
1339 public void run() {
1340 try {
1341 evict();
1342 } catch(Exception e) {
1343
1344 }
1345 try {
1346 ensureMinIdle();
1347 } catch(Exception e) {
1348
1349 }
1350 }
1351 }
1352
1353 /***
1354 * A simple "struct" encapsulating the
1355 * configuration information for a {@link GenericObjectPool}.
1356 * @see GenericObjectPool#GenericObjectPool(org.apache.commons.pool.PoolableObjectFactory,org.apache.commons.pool.impl.GenericObjectPool.Config)
1357 * @see GenericObjectPool#setConfig
1358 */
1359 public static class Config {
1360 /***
1361 * @see GenericObjectPool#setMaxIdle
1362 */
1363 public int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE;
1364 /***
1365 * @see GenericObjectPool#setMinIdle
1366 */
1367 public int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE;
1368 /***
1369 * @see GenericObjectPool#setMaxActive
1370 */
1371 public int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE;
1372 /***
1373 * @see GenericObjectPool#setMaxWait
1374 */
1375 public long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT;
1376 /***
1377 * @see GenericObjectPool#setWhenExhaustedAction
1378 */
1379 public byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
1380 /***
1381 * @see GenericObjectPool#setTestOnBorrow
1382 */
1383 public boolean testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
1384 /***
1385 * @see GenericObjectPool#setTestOnReturn
1386 */
1387 public boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
1388 /***
1389 * @see GenericObjectPool#setTestWhileIdle
1390 */
1391 public boolean testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
1392 /***
1393 * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis
1394 */
1395 public long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
1396 /***
1397 * @see GenericObjectPool#setNumTestsPerEvictionRun
1398 */
1399 public int numTestsPerEvictionRun = GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
1400 /***
1401 * @see GenericObjectPool#setMinEvictableIdleTimeMillis
1402 */
1403 public long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1404 /***
1405 * @see GenericObjectPool#setSoftMinEvictableIdleTimeMillis
1406 */
1407 public long softMinEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1408 /***
1409 * @see GenericObjectPool#setLifo
1410 */
1411 public boolean lifo = GenericObjectPool.DEFAULT_LIFO;
1412
1413 }
1414
1415
1416
1417 /***
1418 * The cap on the number of idle instances in the pool.
1419 * @see #setMaxIdle
1420 * @see #getMaxIdle
1421 */
1422 private int _maxIdle = DEFAULT_MAX_IDLE;
1423
1424 /***
1425 * The cap on the minimum number of idle instances in the pool.
1426 * @see #setMinIdle
1427 * @see #getMinIdle
1428 */
1429 private int _minIdle = DEFAULT_MIN_IDLE;
1430
1431 /***
1432 * The cap on the total number of active instances from the pool.
1433 * @see #setMaxActive
1434 * @see #getMaxActive
1435 */
1436 private int _maxActive = DEFAULT_MAX_ACTIVE;
1437
1438 /***
1439 * The maximum amount of time (in millis) the
1440 * {@link #borrowObject} method should block before throwing
1441 * an exception when the pool is exhausted and the
1442 * {@link #getWhenExhaustedAction "when exhausted" action} is
1443 * {@link #WHEN_EXHAUSTED_BLOCK}.
1444 *
1445 * When less than or equal to 0, the {@link #borrowObject} method
1446 * may block indefinitely.
1447 *
1448 * @see #setMaxWait
1449 * @see #getMaxWait
1450 * @see #WHEN_EXHAUSTED_BLOCK
1451 * @see #setWhenExhaustedAction
1452 * @see #getWhenExhaustedAction
1453 */
1454 private long _maxWait = DEFAULT_MAX_WAIT;
1455
1456 /***
1457 * The action to take when the {@link #borrowObject} method
1458 * is invoked when the pool is exhausted (the maximum number
1459 * of "active" objects has been reached).
1460 *
1461 * @see #WHEN_EXHAUSTED_BLOCK
1462 * @see #WHEN_EXHAUSTED_FAIL
1463 * @see #WHEN_EXHAUSTED_GROW
1464 * @see #DEFAULT_WHEN_EXHAUSTED_ACTION
1465 * @see #setWhenExhaustedAction
1466 * @see #getWhenExhaustedAction
1467 */
1468 private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION;
1469
1470 /***
1471 * When <tt>true</tt>, objects will be
1472 * {@link PoolableObjectFactory#validateObject validated}
1473 * before being returned by the {@link #borrowObject}
1474 * method. If the object fails to validate,
1475 * it will be dropped from the pool, and we will attempt
1476 * to borrow another.
1477 *
1478 * @see #setTestOnBorrow
1479 * @see #getTestOnBorrow
1480 */
1481 private volatile boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW;
1482
1483 /***
1484 * When <tt>true</tt>, objects will be
1485 * {@link PoolableObjectFactory#validateObject validated}
1486 * before being returned to the pool within the
1487 * {@link #returnObject}.
1488 *
1489 * @see #getTestOnReturn
1490 * @see #setTestOnReturn
1491 */
1492 private volatile boolean _testOnReturn = DEFAULT_TEST_ON_RETURN;
1493
1494 /***
1495 * When <tt>true</tt>, objects will be
1496 * {@link PoolableObjectFactory#validateObject validated}
1497 * by the idle object evictor (if any). If an object
1498 * fails to validate, it will be dropped from the pool.
1499 *
1500 * @see #setTestWhileIdle
1501 * @see #getTestWhileIdle
1502 * @see #getTimeBetweenEvictionRunsMillis
1503 * @see #setTimeBetweenEvictionRunsMillis
1504 */
1505 private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE;
1506
1507 /***
1508 * The number of milliseconds to sleep between runs of the
1509 * idle object evictor thread.
1510 * When non-positive, no idle object evictor thread will be
1511 * run.
1512 *
1513 * @see #setTimeBetweenEvictionRunsMillis
1514 * @see #getTimeBetweenEvictionRunsMillis
1515 */
1516 private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
1517
1518 /***
1519 * The max number of objects to examine during each run of the
1520 * idle object evictor thread (if any).
1521 * <p>
1522 * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
1523 * tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
1524 * idle objects will be tested per run.
1525 *
1526 * @see #setNumTestsPerEvictionRun
1527 * @see #getNumTestsPerEvictionRun
1528 * @see #getTimeBetweenEvictionRunsMillis
1529 * @see #setTimeBetweenEvictionRunsMillis
1530 */
1531 private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
1532
1533 /***
1534 * The minimum amount of time an object may sit idle in the pool
1535 * before it is eligible for eviction by the idle object evictor
1536 * (if any).
1537 * When non-positive, no objects will be evicted from the pool
1538 * due to idle time alone.
1539 *
1540 * @see #setMinEvictableIdleTimeMillis
1541 * @see #getMinEvictableIdleTimeMillis
1542 * @see #getTimeBetweenEvictionRunsMillis
1543 * @see #setTimeBetweenEvictionRunsMillis
1544 */
1545 private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1546
1547 /***
1548 * The minimum amount of time an object may sit idle in the pool
1549 * before it is eligible for eviction by the idle object evictor
1550 * (if any), with the extra condition that at least
1551 * "minIdle" amount of object remain in the pool.
1552 * When non-positive, no objects will be evicted from the pool
1553 * due to idle time alone.
1554 *
1555 * @see #setSoftMinEvictableIdleTimeMillis
1556 * @see #getSoftMinEvictableIdleTimeMillis
1557 */
1558 private long _softMinEvictableIdleTimeMillis = DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1559
1560 /*** Whether or not the pool behaves as a LIFO queue (last in first out) */
1561 private boolean _lifo = DEFAULT_LIFO;
1562
1563 /*** My pool. */
1564 private CursorableLinkedList _pool = null;
1565
1566 /*** Eviction cursor - keeps track of idle object evictor position */
1567 private CursorableLinkedList.Cursor _evictionCursor = null;
1568
1569 /*** My {@link PoolableObjectFactory}. */
1570 private PoolableObjectFactory _factory = null;
1571
1572 /***
1573 * The number of objects {@link #borrowObject} borrowed
1574 * from the pool, but not yet returned.
1575 */
1576 private int _numActive = 0;
1577
1578 /***
1579 * My idle object eviction {@link TimerTask}, if any.
1580 */
1581 private Evictor _evictor = null;
1582
1583 }