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