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