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