Source Code Cross Referenced for GenericObjectPool.java in  » Web-Crawler » heritrix » org » apache » commons » pool » impl » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Web Crawler » heritrix » org.apache.commons.pool.impl 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * Copyright 1999-2004 The Apache Software Foundation.
0003:         * 
0004:         * Licensed under the Apache License, Version 2.0 (the "License");
0005:         * you may not use this file except in compliance with the License.
0006:         * You may obtain a copy of the License at
0007:         * 
0008:         *      http://www.apache.org/licenses/LICENSE-2.0
0009:         * 
0010:         * Unless required by applicable law or agreed to in writing, software
0011:         * distributed under the License is distributed on an "AS IS" BASIS,
0012:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0013:         * See the License for the specific language governing permissions and
0014:         * limitations under the License.
0015:         */
0016:
0017:        package org.apache.commons.pool.impl;
0018:
0019:        import java.util.Iterator;
0020:        import java.util.NoSuchElementException;
0021:        import java.util.LinkedList;
0022:        import java.util.ListIterator;
0023:        import java.util.Timer;
0024:        import java.util.TimerTask;
0025:
0026:        import org.apache.commons.pool.BaseObjectPool;
0027:        import org.apache.commons.pool.ObjectPool;
0028:        import org.apache.commons.pool.PoolableObjectFactory;
0029:        import org.apache.commons.pool.impl.GenericKeyedObjectPool.ObjectTimestampPair;
0030:
0031:        /**
0032:         * A configurable {@link ObjectPool} implementation.
0033:         * <p>
0034:         * When coupled with the appropriate {@link PoolableObjectFactory},
0035:         * <tt>GenericObjectPool</tt> provides robust pooling functionality for
0036:         * arbitrary objects.
0037:         * <p>
0038:         * A <tt>GenericObjectPool</tt> provides a number of configurable parameters:
0039:         * <ul>
0040:         *  <li>
0041:         *    {@link #setMaxActive <i>maxActive</i>} controls the maximum number of objects that can
0042:         *    be borrowed from the pool at one time.  When non-positive, there
0043:         *    is no limit to the number of objects that may be active at one time.
0044:         *    When {@link #setMaxActive <i>maxActive</i>} is exceeded, the pool is said to be exhausted.
0045:         *  </li>
0046:         *  <li>
0047:         *    {@link #setMaxIdle <i>maxIdle</i>} controls the maximum number of objects that can
0048:         *    sit idle in the pool at any time.  When negative, there
0049:         *    is no limit to the number of objects that may be idle at one time.
0050:         *  </li>
0051:         *  <li>
0052:         *    {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} specifies the
0053:         *    behaviour of the {@link #borrowObject} method when the pool is exhausted:
0054:         *    <ul>
0055:         *    <li>
0056:         *      When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
0057:         *      {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject} will throw
0058:         *      a {@link NoSuchElementException}
0059:         *    </li>
0060:         *    <li>
0061:         *      When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
0062:         *      {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject} will create a new
0063:         *      object and return it(essentially making {@link #setMaxActive <i>maxActive</i>}
0064:         *      meaningless.)
0065:         *    </li>
0066:         *    <li>
0067:         *      When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>}
0068:         *      is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject} will block
0069:         *      (invoke {@link Object#wait} until a new or idle object is available.
0070:         *      If a positive {@link #setMaxWait <i>maxWait</i>}
0071:         *      value is supplied, the {@link #borrowObject} will block for at
0072:         *      most that many milliseconds, after which a {@link NoSuchElementException}
0073:         *      will be thrown.  If {@link #setMaxWait <i>maxWait</i>} is non-positive,
0074:         *      the {@link #borrowObject} method will block indefinitely.
0075:         *    </li>
0076:         *    </ul>
0077:         *  </li>
0078:         *  <li>
0079:         *    When {@link #setTestOnBorrow <i>testOnBorrow</i>} is set, the pool will
0080:         *    attempt to validate each object before it is returned from the
0081:         *    {@link #borrowObject} method. (Using the provided factory's
0082:         *    {@link PoolableObjectFactory#validateObject} method.)  Objects that fail
0083:         *    to validate will be dropped from the pool, and a different object will
0084:         *    be borrowed.
0085:         *  </li>
0086:         *  <li>
0087:         *    When {@link #setTestOnReturn <i>testOnReturn</i>} is set, the pool will
0088:         *    attempt to validate each object before it is returned to the pool in the
0089:         *    {@link #returnObject} method. (Using the provided factory's
0090:         *    {@link PoolableObjectFactory#validateObject}
0091:         *    method.)  Objects that fail to validate will be dropped from the pool.
0092:         *  </li>
0093:         * </ul>
0094:         * <p>
0095:         * Optionally, one may configure the pool to examine and possibly evict objects as they
0096:         * sit idle in the pool.  This is performed by an "idle object eviction" thread, which
0097:         * runs asychronously.  The idle object eviction thread may be configured using the
0098:         * following attributes:
0099:         * <ul>
0100:         *  <li>
0101:         *   {@link #setTimeBetweenEvictionRunsMillis <i>timeBetweenEvictionRunsMillis</i>}
0102:         *   indicates how long the eviction thread should sleep before "runs" of examining
0103:         *   idle objects.  When non-positive, no eviction thread will be launched.
0104:         *  </li>
0105:         *  <li>
0106:         *   {@link #setMinEvictableIdleTimeMillis <i>minEvictableIdleTimeMillis</i>}
0107:         *   specifies the minimum amount of time that an object may sit idle in the pool
0108:         *   before it is eligable for eviction due to idle time.  When non-positive, no object
0109:         *   will be dropped from the pool due to idle time alone.
0110:         *  </li>
0111:         *  <li>
0112:         *   {@link #setTestWhileIdle <i>testWhileIdle</i>} indicates whether or not idle
0113:         *   objects should be validated using the factory's
0114:         *   {@link PoolableObjectFactory#validateObject} method.  Objects
0115:         *   that fail to validate will be dropped from the pool.
0116:         *  </li>
0117:         * </ul>
0118:         * <p>
0119:         * GenericObjectPool is not usable without a {@link PoolableObjectFactory}.  A
0120:         * non-<code>null</code> factory must be provided either as a constructor argument
0121:         * or via a call to {@link #setFactory} before the pool is used.
0122:         *
0123:         * @see GenericKeyedObjectPool
0124:         * @author Rodney Waldhoff
0125:         * @author Dirk Verbeeck
0126:         * @version $Revision: 4672 $ $Date: 2006-09-27 00:03:16 +0000 (Wed, 27 Sep 2006) $
0127:         */
0128:        @SuppressWarnings("unchecked")
0129:        public class GenericObjectPool extends BaseObjectPool implements 
0130:                ObjectPool {
0131:
0132:            //--- public constants -------------------------------------------
0133:
0134:            /**
0135:             * A "when exhausted action" type indicating that when the pool is
0136:             * exhausted (i.e., the maximum number of active objects has
0137:             * been reached), the {@link #borrowObject}
0138:             * method should fail, throwing a {@link NoSuchElementException}.
0139:             * @see #WHEN_EXHAUSTED_BLOCK
0140:             * @see #WHEN_EXHAUSTED_GROW
0141:             * @see #setWhenExhaustedAction
0142:             */
0143:            public static final byte WHEN_EXHAUSTED_FAIL = 0;
0144:
0145:            /**
0146:             * A "when exhausted action" type indicating that when the pool
0147:             * is exhausted (i.e., the maximum number
0148:             * of active objects has been reached), the {@link #borrowObject}
0149:             * method should block until a new object is available, or the
0150:             * {@link #getMaxWait maximum wait time} has been reached.
0151:             * @see #WHEN_EXHAUSTED_FAIL
0152:             * @see #WHEN_EXHAUSTED_GROW
0153:             * @see #setMaxWait
0154:             * @see #getMaxWait
0155:             * @see #setWhenExhaustedAction
0156:             */
0157:            public static final byte WHEN_EXHAUSTED_BLOCK = 1;
0158:
0159:            /**
0160:             * A "when exhausted action" type indicating that when the pool is
0161:             * exhausted (i.e., the maximum number
0162:             * of active objects has been reached), the {@link #borrowObject}
0163:             * method should simply create a new object anyway.
0164:             * @see #WHEN_EXHAUSTED_FAIL
0165:             * @see #WHEN_EXHAUSTED_GROW
0166:             * @see #setWhenExhaustedAction
0167:             */
0168:            public static final byte WHEN_EXHAUSTED_GROW = 2;
0169:
0170:            /**
0171:             * The default cap on the number of "sleeping" instances in the pool.
0172:             * @see #getMaxIdle
0173:             * @see #setMaxIdle
0174:             */
0175:            public static final int DEFAULT_MAX_IDLE = 8;
0176:
0177:            /**
0178:             * The default minimum number of "sleeping" instances in the pool
0179:             * before before the evictor thread (if active) spawns new objects.
0180:             * @see #getMinIdle
0181:             * @see #setMinIdle
0182:             */
0183:            public static final int DEFAULT_MIN_IDLE = 0;
0184:
0185:            /**
0186:             * The default cap on the total number of active instances from the pool.
0187:             * @see #getMaxActive
0188:             */
0189:            public static final int DEFAULT_MAX_ACTIVE = 8;
0190:
0191:            /**
0192:             * The default "when exhausted action" for the pool.
0193:             * @see #WHEN_EXHAUSTED_BLOCK
0194:             * @see #WHEN_EXHAUSTED_FAIL
0195:             * @see #WHEN_EXHAUSTED_GROW
0196:             * @see #setWhenExhaustedAction
0197:             */
0198:            public static final byte DEFAULT_WHEN_EXHAUSTED_ACTION = WHEN_EXHAUSTED_BLOCK;
0199:
0200:            /**
0201:             * The default maximum amount of time (in millis) the
0202:             * {@link #borrowObject} method should block before throwing
0203:             * an exception when the pool is exhausted and the
0204:             * {@link #getWhenExhaustedAction "when exhausted" action} is
0205:             * {@link #WHEN_EXHAUSTED_BLOCK}.
0206:             * @see #getMaxWait
0207:             * @see #setMaxWait
0208:             */
0209:            public static final long DEFAULT_MAX_WAIT = -1L;
0210:
0211:            /**
0212:             * The default "test on borrow" value.
0213:             * @see #getTestOnBorrow
0214:             * @see #setTestOnBorrow
0215:             */
0216:            public static final boolean DEFAULT_TEST_ON_BORROW = false;
0217:
0218:            /**
0219:             * The default "test on return" value.
0220:             * @see #getTestOnReturn
0221:             * @see #setTestOnReturn
0222:             */
0223:            public static final boolean DEFAULT_TEST_ON_RETURN = false;
0224:
0225:            /**
0226:             * The default "test while idle" value.
0227:             * @see #getTestWhileIdle
0228:             * @see #setTestWhileIdle
0229:             * @see #getTimeBetweenEvictionRunsMillis
0230:             * @see #setTimeBetweenEvictionRunsMillis
0231:             */
0232:            public static final boolean DEFAULT_TEST_WHILE_IDLE = false;
0233:
0234:            /**
0235:             * The default "time between eviction runs" value.
0236:             * @see #getTimeBetweenEvictionRunsMillis
0237:             * @see #setTimeBetweenEvictionRunsMillis
0238:             */
0239:            public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L;
0240:
0241:            /**
0242:             * The default number of objects to examine per run in the
0243:             * idle object evictor.
0244:             * @see #getNumTestsPerEvictionRun
0245:             * @see #setNumTestsPerEvictionRun
0246:             * @see #getTimeBetweenEvictionRunsMillis
0247:             * @see #setTimeBetweenEvictionRunsMillis
0248:             */
0249:            public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3;
0250:
0251:            /**
0252:             * The default value for {@link #getMinEvictableIdleTimeMillis}.
0253:             * @see #getMinEvictableIdleTimeMillis
0254:             * @see #setMinEvictableIdleTimeMillis
0255:             */
0256:            public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L;
0257:
0258:            /**
0259:             * The default value for {@link #getSoftMinEvictableIdleTimeMillis}.
0260:             * @see #getSoftMinEvictableIdleTimeMillis
0261:             * @see #setSoftMinEvictableIdleTimeMillis
0262:             */
0263:            public static final long DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = -1;
0264:
0265:            //--- package constants -------------------------------------------
0266:
0267:            /**
0268:             * Idle object evition Timer. Shared between all {@link GenericObjectPool}s and {@link GenericKeyedObjectPool} s.
0269:             */
0270:            static final Timer EVICTION_TIMER = new Timer(true);
0271:
0272:            //--- constructors -----------------------------------------------
0273:
0274:            /**
0275:             * Create a new <tt>GenericObjectPool</tt>.
0276:             */
0277:            public GenericObjectPool() {
0278:                this (null, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION,
0279:                        DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, DEFAULT_MIN_IDLE,
0280:                        DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN,
0281:                        DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
0282:                        DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
0283:                        DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
0284:                        DEFAULT_TEST_WHILE_IDLE);
0285:            }
0286:
0287:            /**
0288:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0289:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0290:             */
0291:            public GenericObjectPool(PoolableObjectFactory factory) {
0292:                this (factory, DEFAULT_MAX_ACTIVE,
0293:                        DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT,
0294:                        DEFAULT_MAX_IDLE, DEFAULT_MIN_IDLE,
0295:                        DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN,
0296:                        DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
0297:                        DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
0298:                        DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
0299:                        DEFAULT_TEST_WHILE_IDLE);
0300:            }
0301:
0302:            /**
0303:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0304:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0305:             * @param config a non-<tt>null</tt> {@link GenericObjectPool.Config} describing my configuration
0306:             */
0307:            public GenericObjectPool(PoolableObjectFactory factory,
0308:                    GenericObjectPool.Config config) {
0309:                this (factory, config.maxActive, config.whenExhaustedAction,
0310:                        config.maxWait, config.maxIdle, config.minIdle,
0311:                        config.testOnBorrow, config.testOnReturn,
0312:                        config.timeBetweenEvictionRunsMillis,
0313:                        config.numTestsPerEvictionRun,
0314:                        config.minEvictableIdleTimeMillis, config.testWhileIdle);
0315:            }
0316:
0317:            /**
0318:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0319:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0320:             * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
0321:             */
0322:            public GenericObjectPool(PoolableObjectFactory factory,
0323:                    int maxActive) {
0324:                this (factory, maxActive, DEFAULT_WHEN_EXHAUSTED_ACTION,
0325:                        DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, DEFAULT_MIN_IDLE,
0326:                        DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN,
0327:                        DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
0328:                        DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
0329:                        DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
0330:                        DEFAULT_TEST_WHILE_IDLE);
0331:            }
0332:
0333:            /**
0334:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0335:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0336:             * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
0337:             * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
0338:             * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
0339:             */
0340:            public GenericObjectPool(PoolableObjectFactory factory,
0341:                    int maxActive, byte whenExhaustedAction, long maxWait) {
0342:                this (factory, maxActive, whenExhaustedAction, maxWait,
0343:                        DEFAULT_MAX_IDLE, DEFAULT_MIN_IDLE,
0344:                        DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN,
0345:                        DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
0346:                        DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
0347:                        DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
0348:                        DEFAULT_TEST_WHILE_IDLE);
0349:            }
0350:
0351:            /**
0352:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0353:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0354:             * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
0355:             * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
0356:             * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
0357:             * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #getTestOnBorrow})
0358:             * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #getTestOnReturn})
0359:             */
0360:            public GenericObjectPool(PoolableObjectFactory factory,
0361:                    int maxActive, byte whenExhaustedAction, long maxWait,
0362:                    boolean testOnBorrow, boolean testOnReturn) {
0363:                this (factory, maxActive, whenExhaustedAction, maxWait,
0364:                        DEFAULT_MAX_IDLE, DEFAULT_MIN_IDLE, testOnBorrow,
0365:                        testOnReturn,
0366:                        DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
0367:                        DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
0368:                        DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
0369:                        DEFAULT_TEST_WHILE_IDLE);
0370:            }
0371:
0372:            /**
0373:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0374:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0375:             * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
0376:             * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
0377:             * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
0378:             * @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle})
0379:             */
0380:            public GenericObjectPool(PoolableObjectFactory factory,
0381:                    int maxActive, byte whenExhaustedAction, long maxWait,
0382:                    int maxIdle) {
0383:                this (factory, maxActive, whenExhaustedAction, maxWait, maxIdle,
0384:                        DEFAULT_MIN_IDLE, DEFAULT_TEST_ON_BORROW,
0385:                        DEFAULT_TEST_ON_RETURN,
0386:                        DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
0387:                        DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
0388:                        DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
0389:                        DEFAULT_TEST_WHILE_IDLE);
0390:            }
0391:
0392:            /**
0393:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0394:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0395:             * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
0396:             * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
0397:             * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
0398:             * @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle})
0399:             * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #getTestOnBorrow})
0400:             * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #getTestOnReturn})
0401:             */
0402:            public GenericObjectPool(PoolableObjectFactory factory,
0403:                    int maxActive, byte whenExhaustedAction, long maxWait,
0404:                    int maxIdle, boolean testOnBorrow, boolean testOnReturn) {
0405:                this (factory, maxActive, whenExhaustedAction, maxWait, maxIdle,
0406:                        DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn,
0407:                        DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
0408:                        DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
0409:                        DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
0410:                        DEFAULT_TEST_WHILE_IDLE);
0411:            }
0412:
0413:            /**
0414:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0415:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0416:             * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
0417:             * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
0418:             * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
0419:             * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
0420:             * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
0421:             * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
0422:             * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
0423:             * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
0424:             * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligable for evcition (see {@link #setMinEvictableIdleTimeMillis})
0425:             * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
0426:             */
0427:            public GenericObjectPool(PoolableObjectFactory factory,
0428:                    int maxActive, byte whenExhaustedAction, long maxWait,
0429:                    int maxIdle, boolean testOnBorrow, boolean testOnReturn,
0430:                    long timeBetweenEvictionRunsMillis,
0431:                    int numTestsPerEvictionRun,
0432:                    long minEvictableIdleTimeMillis, boolean testWhileIdle) {
0433:                this (factory, maxActive, whenExhaustedAction, maxWait, maxIdle,
0434:                        DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn,
0435:                        timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
0436:                        minEvictableIdleTimeMillis, testWhileIdle);
0437:            }
0438:
0439:            /**
0440:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0441:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0442:             * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
0443:             * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
0444:             * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
0445:             * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
0446:             * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle})
0447:             * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
0448:             * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
0449:             * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
0450:             * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
0451:             * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligable for evcition (see {@link #setMinEvictableIdleTimeMillis})
0452:             * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
0453:             */
0454:            public GenericObjectPool(PoolableObjectFactory factory,
0455:                    int maxActive, byte whenExhaustedAction, long maxWait,
0456:                    int maxIdle, int minIdle, boolean testOnBorrow,
0457:                    boolean testOnReturn, long timeBetweenEvictionRunsMillis,
0458:                    int numTestsPerEvictionRun,
0459:                    long minEvictableIdleTimeMillis, boolean testWhileIdle) {
0460:                this (factory, maxActive, whenExhaustedAction, maxWait, maxIdle,
0461:                        minIdle, testOnBorrow, testOnReturn,
0462:                        timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
0463:                        minEvictableIdleTimeMillis, testWhileIdle,
0464:                        DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
0465:            }
0466:
0467:            /**
0468:             * Create a new <tt>GenericObjectPool</tt> using the specified values.
0469:             * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
0470:             * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
0471:             * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
0472:             * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
0473:             * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
0474:             * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle})
0475:             * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
0476:             * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
0477:             * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
0478:             * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
0479:             * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligable for evcition (see {@link #setMinEvictableIdleTimeMillis})
0480:             * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
0481:             * @param softMinEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligable for evcition with the extra condition that at least "minIdle" amount of object remain in the pool. (see {@link #setSoftMinEvictableIdleTimeMillis})
0482:             */
0483:            public GenericObjectPool(PoolableObjectFactory factory,
0484:                    int maxActive, byte whenExhaustedAction, long maxWait,
0485:                    int maxIdle, int minIdle, boolean testOnBorrow,
0486:                    boolean testOnReturn, long timeBetweenEvictionRunsMillis,
0487:                    int numTestsPerEvictionRun,
0488:                    long minEvictableIdleTimeMillis, boolean testWhileIdle,
0489:                    long softMinEvictableIdleTimeMillis) {
0490:                _factory = factory;
0491:                _maxActive = maxActive;
0492:                switch (whenExhaustedAction) {
0493:                case WHEN_EXHAUSTED_BLOCK:
0494:                case WHEN_EXHAUSTED_FAIL:
0495:                case WHEN_EXHAUSTED_GROW:
0496:                    _whenExhaustedAction = whenExhaustedAction;
0497:                    break;
0498:                default:
0499:                    throw new IllegalArgumentException("whenExhaustedAction "
0500:                            + whenExhaustedAction + " not recognized.");
0501:                }
0502:                _maxWait = maxWait;
0503:                _maxIdle = maxIdle;
0504:                _minIdle = minIdle;
0505:                _testOnBorrow = testOnBorrow;
0506:                _testOnReturn = testOnReturn;
0507:                _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
0508:                _numTestsPerEvictionRun = numTestsPerEvictionRun;
0509:                _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
0510:                _softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
0511:                _testWhileIdle = testWhileIdle;
0512:
0513:                _pool = new LinkedList();
0514:                startEvictor(_timeBetweenEvictionRunsMillis);
0515:            }
0516:
0517:            //--- public methods ---------------------------------------------
0518:
0519:            //--- configuration methods --------------------------------------
0520:
0521:            /**
0522:             * Returns the cap on the total number of active instances from my pool.
0523:             * @return the cap on the total number of active instances from my pool.
0524:             * @see #setMaxActive
0525:             */
0526:            public synchronized int getMaxActive() {
0527:                return _maxActive;
0528:            }
0529:
0530:            /**
0531:             * Sets the cap on the total number of active instances from my pool.
0532:             * @param maxActive The cap on the total number of active instances from my pool.
0533:             *                  Use a negative value for an infinite number of instances.
0534:             * @see #getMaxActive
0535:             */
0536:            public synchronized void setMaxActive(int maxActive) {
0537:                _maxActive = maxActive;
0538:                notifyAll();
0539:            }
0540:
0541:            /**
0542:             * Returns the action to take when the {@link #borrowObject} method
0543:             * is invoked when the pool is exhausted (the maximum number
0544:             * of "active" objects has been reached).
0545:             *
0546:             * @return one of {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW}
0547:             * @see #setWhenExhaustedAction
0548:             */
0549:            public synchronized byte getWhenExhaustedAction() {
0550:                return _whenExhaustedAction;
0551:            }
0552:
0553:            /**
0554:             * Sets the action to take when the {@link #borrowObject} method
0555:             * is invoked when the pool is exhausted (the maximum number
0556:             * of "active" objects has been reached).
0557:             *
0558:             * @param whenExhaustedAction the action code, which must be one of
0559:             *        {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL},
0560:             *        or {@link #WHEN_EXHAUSTED_GROW}
0561:             * @see #getWhenExhaustedAction
0562:             */
0563:            public synchronized void setWhenExhaustedAction(
0564:                    byte whenExhaustedAction) {
0565:                switch (whenExhaustedAction) {
0566:                case WHEN_EXHAUSTED_BLOCK:
0567:                case WHEN_EXHAUSTED_FAIL:
0568:                case WHEN_EXHAUSTED_GROW:
0569:                    _whenExhaustedAction = whenExhaustedAction;
0570:                    notifyAll();
0571:                    break;
0572:                default:
0573:                    throw new IllegalArgumentException("whenExhaustedAction "
0574:                            + whenExhaustedAction + " not recognized.");
0575:                }
0576:            }
0577:
0578:            /**
0579:             * Returns the maximum amount of time (in milliseconds) the
0580:             * {@link #borrowObject} method should block before throwing
0581:             * an exception when the pool is exhausted and the
0582:             * {@link #setWhenExhaustedAction "when exhausted" action} is
0583:             * {@link #WHEN_EXHAUSTED_BLOCK}.
0584:             *
0585:             * When less than 0, the {@link #borrowObject} method
0586:             * may block indefinitely.
0587:             *
0588:             * @see #setMaxWait
0589:             * @see #setWhenExhaustedAction
0590:             * @see #WHEN_EXHAUSTED_BLOCK
0591:             */
0592:            public synchronized long getMaxWait() {
0593:                return _maxWait;
0594:            }
0595:
0596:            /**
0597:             * Sets the maximum amount of time (in milliseconds) the
0598:             * {@link #borrowObject} method should block before throwing
0599:             * an exception when the pool is exhausted and the
0600:             * {@link #setWhenExhaustedAction "when exhausted" action} is
0601:             * {@link #WHEN_EXHAUSTED_BLOCK}.
0602:             *
0603:             * When less than 0, the {@link #borrowObject} method
0604:             * may block indefinitely.
0605:             *
0606:             * @see #getMaxWait
0607:             * @see #setWhenExhaustedAction
0608:             * @see #WHEN_EXHAUSTED_BLOCK
0609:             */
0610:            public synchronized void setMaxWait(long maxWait) {
0611:                _maxWait = maxWait;
0612:                notifyAll();
0613:            }
0614:
0615:            /**
0616:             * Returns the cap on the number of "idle" instances in the pool.
0617:             * @return the cap on the number of "idle" instances in the pool.
0618:             * @see #setMaxIdle
0619:             */
0620:            public synchronized int getMaxIdle() {
0621:                return _maxIdle;
0622:            }
0623:
0624:            /**
0625:             * Sets the cap on the number of "idle" instances in the pool.
0626:             * @param maxIdle The cap on the number of "idle" instances in the pool.
0627:             *                Use a negative value to indicate an unlimited number
0628:             *                of idle instances.
0629:             * @see #getMaxIdle
0630:             */
0631:            public synchronized void setMaxIdle(int maxIdle) {
0632:                _maxIdle = maxIdle;
0633:                notifyAll();
0634:            }
0635:
0636:            /**
0637:             * Sets the minimum number of objects allowed in the pool
0638:             * before the evictor thread (if active) spawns new objects.
0639:             * (Note no objects are created when: numActive + numIdle >= maxActive)
0640:             *
0641:             * @param minIdle The minimum number of objects.
0642:             * @see #getMinIdle
0643:             */
0644:            public synchronized void setMinIdle(int minIdle) {
0645:                _minIdle = minIdle;
0646:                notifyAll();
0647:            }
0648:
0649:            /**
0650:             * Returns the minimum number of objects allowed in the pool
0651:             * before the evictor thread (if active) spawns new objects.
0652:             * (Note no objects are created when: numActive + numIdle >= maxActive)
0653:             *
0654:             * @return The minimum number of objects.
0655:             * @see #setMinIdle
0656:             */
0657:            public synchronized int getMinIdle() {
0658:                return _minIdle;
0659:            }
0660:
0661:            /**
0662:             * When <tt>true</tt>, objects will be
0663:             * {@link PoolableObjectFactory#validateObject validated}
0664:             * before being returned by the {@link #borrowObject}
0665:             * method.  If the object fails to validate,
0666:             * it will be dropped from the pool, and we will attempt
0667:             * to borrow another.
0668:             *
0669:             * @see #setTestOnBorrow
0670:             */
0671:            public synchronized boolean getTestOnBorrow() {
0672:                return _testOnBorrow;
0673:            }
0674:
0675:            /**
0676:             * When <tt>true</tt>, objects will be
0677:             * {@link PoolableObjectFactory#validateObject validated}
0678:             * before being returned by the {@link #borrowObject}
0679:             * method.  If the object fails to validate,
0680:             * it will be dropped from the pool, and we will attempt
0681:             * to borrow another.
0682:             *
0683:             * @see #getTestOnBorrow
0684:             */
0685:            public synchronized void setTestOnBorrow(boolean testOnBorrow) {
0686:                _testOnBorrow = testOnBorrow;
0687:            }
0688:
0689:            /**
0690:             * When <tt>true</tt>, objects will be
0691:             * {@link PoolableObjectFactory#validateObject validated}
0692:             * before being returned to the pool within the
0693:             * {@link #returnObject}.
0694:             *
0695:             * @see #setTestOnReturn
0696:             */
0697:            public synchronized boolean getTestOnReturn() {
0698:                return _testOnReturn;
0699:            }
0700:
0701:            /**
0702:             * When <tt>true</tt>, objects will be
0703:             * {@link PoolableObjectFactory#validateObject validated}
0704:             * before being returned to the pool within the
0705:             * {@link #returnObject}.
0706:             *
0707:             * @see #getTestOnReturn
0708:             */
0709:            public synchronized void setTestOnReturn(boolean testOnReturn) {
0710:                _testOnReturn = testOnReturn;
0711:            }
0712:
0713:            /**
0714:             * Returns the number of milliseconds to sleep between runs of the
0715:             * idle object evictor thread.
0716:             * When non-positive, no idle object evictor thread will be
0717:             * run.
0718:             *
0719:             * @see #setTimeBetweenEvictionRunsMillis
0720:             */
0721:            public synchronized long getTimeBetweenEvictionRunsMillis() {
0722:                return _timeBetweenEvictionRunsMillis;
0723:            }
0724:
0725:            /**
0726:             * Sets the number of milliseconds to sleep between runs of the
0727:             * idle object evictor thread.
0728:             * When non-positive, no idle object evictor thread will be
0729:             * run.
0730:             *
0731:             * @see #getTimeBetweenEvictionRunsMillis
0732:             */
0733:            public synchronized void setTimeBetweenEvictionRunsMillis(
0734:                    long timeBetweenEvictionRunsMillis) {
0735:                _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
0736:                startEvictor(_timeBetweenEvictionRunsMillis);
0737:            }
0738:
0739:            /**
0740:             * Returns the max number of objects to examine during each run of the
0741:             * idle object evictor thread (if any).
0742:             *
0743:             * @see #setNumTestsPerEvictionRun
0744:             * @see #setTimeBetweenEvictionRunsMillis
0745:             */
0746:            public synchronized int getNumTestsPerEvictionRun() {
0747:                return _numTestsPerEvictionRun;
0748:            }
0749:
0750:            /**
0751:             * Sets the max number of objects to examine during each run of the
0752:             * idle object evictor thread (if any).
0753:             * <p>
0754:             * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
0755:             * tests will be run.  I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
0756:             * idle objects will be tested per run.
0757:             *
0758:             * @see #getNumTestsPerEvictionRun
0759:             * @see #setTimeBetweenEvictionRunsMillis
0760:             */
0761:            public synchronized void setNumTestsPerEvictionRun(
0762:                    int numTestsPerEvictionRun) {
0763:                _numTestsPerEvictionRun = numTestsPerEvictionRun;
0764:            }
0765:
0766:            /**
0767:             * Returns the minimum amount of time an object may sit idle in the pool
0768:             * before it is eligable for eviction by the idle object evictor
0769:             * (if any).
0770:             *
0771:             * @see #setMinEvictableIdleTimeMillis
0772:             * @see #setTimeBetweenEvictionRunsMillis
0773:             */
0774:            public synchronized long getMinEvictableIdleTimeMillis() {
0775:                return _minEvictableIdleTimeMillis;
0776:            }
0777:
0778:            /**
0779:             * Sets the minimum amount of time an object may sit idle in the pool
0780:             * before it is eligable for eviction by the idle object evictor
0781:             * (if any).
0782:             * When non-positive, no objects will be evicted from the pool
0783:             * due to idle time alone.
0784:             *
0785:             * @see #getMinEvictableIdleTimeMillis
0786:             * @see #setTimeBetweenEvictionRunsMillis
0787:             */
0788:            public synchronized void setMinEvictableIdleTimeMillis(
0789:                    long minEvictableIdleTimeMillis) {
0790:                _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
0791:            }
0792:
0793:            /**
0794:             * Returns the minimum amount of time an object may sit idle in the pool
0795:             * before it is eligable for eviction by the idle object evictor
0796:             * (if any), with the extra condition that at least
0797:             * "minIdle" amount of object remain in the pool.
0798:             *
0799:             * @see #setSoftMinEvictableIdleTimeMillis
0800:             */
0801:            public synchronized long getSoftMinEvictableIdleTimeMillis() {
0802:                return _softMinEvictableIdleTimeMillis;
0803:            }
0804:
0805:            /**
0806:             * Sets the minimum amount of time an object may sit idle in the pool
0807:             * before it is eligable for eviction by the idle object evictor
0808:             * (if any), with the extra condition that at least
0809:             * "minIdle" amount of object remain in the pool.
0810:             * When non-positive, no objects will be evicted from the pool
0811:             * due to idle time alone.
0812:             *
0813:             * @see #getSoftMinEvictableIdleTimeMillis
0814:             */
0815:            public synchronized void setSoftMinEvictableIdleTimeMillis(
0816:                    long softMinEvictableIdleTimeMillis) {
0817:                _softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
0818:            }
0819:
0820:            /**
0821:             * When <tt>true</tt>, objects will be
0822:             * {@link PoolableObjectFactory#validateObject validated}
0823:             * by the idle object evictor (if any).  If an object
0824:             * fails to validate, it will be dropped from the pool.
0825:             *
0826:             * @see #setTestWhileIdle
0827:             * @see #setTimeBetweenEvictionRunsMillis
0828:             */
0829:            public synchronized boolean getTestWhileIdle() {
0830:                return _testWhileIdle;
0831:            }
0832:
0833:            /**
0834:             * When <tt>true</tt>, objects will be
0835:             * {@link PoolableObjectFactory#validateObject validated}
0836:             * by the idle object evictor (if any).  If an object
0837:             * fails to validate, it will be dropped from the pool.
0838:             *
0839:             * @see #getTestWhileIdle
0840:             * @see #setTimeBetweenEvictionRunsMillis
0841:             */
0842:            public synchronized void setTestWhileIdle(boolean testWhileIdle) {
0843:                _testWhileIdle = testWhileIdle;
0844:            }
0845:
0846:            /**
0847:             * Sets my configuration.
0848:             * @see GenericObjectPool.Config
0849:             */
0850:            public synchronized void setConfig(GenericObjectPool.Config conf) {
0851:                setMaxIdle(conf.maxIdle);
0852:                setMinIdle(conf.minIdle);
0853:                setMaxActive(conf.maxActive);
0854:                setMaxWait(conf.maxWait);
0855:                setWhenExhaustedAction(conf.whenExhaustedAction);
0856:                setTestOnBorrow(conf.testOnBorrow);
0857:                setTestOnReturn(conf.testOnReturn);
0858:                setTestWhileIdle(conf.testWhileIdle);
0859:                setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun);
0860:                setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
0861:                setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
0862:                notifyAll();
0863:            }
0864:
0865:            //-- ObjectPool methods ------------------------------------------
0866:
0867:            public synchronized Object borrowObject() throws Exception {
0868:                assertOpen();
0869:                long starttime = System.currentTimeMillis();
0870:                for (;;) {
0871:                    ObjectTimestampPair pair = null;
0872:
0873:                    // if there are any sleeping, just grab one of those
0874:                    try {
0875:                        pair = (ObjectTimestampPair) (_pool.removeFirst());
0876:                    } catch (NoSuchElementException e) {
0877:                        ; /* ignored */
0878:                    }
0879:
0880:                    // otherwise
0881:                    if (null == pair) {
0882:                        // check if we can create one
0883:                        // (note we know that the num sleeping is 0, else we wouldn't be here)
0884:                        if (_maxActive < 0 || _numActive < _maxActive) {
0885:                            // allow new object to be created
0886:                        } else {
0887:                            // the pool is exhausted
0888:                            switch (_whenExhaustedAction) {
0889:                            case WHEN_EXHAUSTED_GROW:
0890:                                // allow new object to be created
0891:                                break;
0892:                            case WHEN_EXHAUSTED_FAIL:
0893:                                throw new NoSuchElementException(
0894:                                        "Pool exhausted");
0895:                            case WHEN_EXHAUSTED_BLOCK:
0896:                                try {
0897:                                    if (_maxWait <= 0) {
0898:                                        wait();
0899:                                    } else {
0900:                                        // this code may be executed again after a notify then continue cycle
0901:                                        // so, need to calculate the amount of time to wait
0902:                                        final long elapsed = (System
0903:                                                .currentTimeMillis() - starttime);
0904:                                        final long waitTime = _maxWait
0905:                                                - elapsed;
0906:                                        if (waitTime > 0) {
0907:                                            wait(waitTime);
0908:                                        }
0909:                                    }
0910:                                } catch (InterruptedException e) {
0911:                                    // ignored
0912:                                }
0913:                                if (_maxWait > 0
0914:                                        && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
0915:                                    throw new NoSuchElementException(
0916:                                            "Timeout waiting for idle object");
0917:                                } else {
0918:                                    continue; // keep looping
0919:                                }
0920:                            default:
0921:                                throw new IllegalArgumentException(
0922:                                        "WhenExhaustedAction property "
0923:                                                + _whenExhaustedAction
0924:                                                + " not recognized.");
0925:                            }
0926:                        }
0927:                    }
0928:                    _numActive++;
0929:
0930:                    // create new object when needed
0931:                    boolean newlyCreated = false;
0932:                    if (null == pair) {
0933:                        try {
0934:                            Object obj = _factory.makeObject();
0935:                            pair = new ObjectTimestampPair(obj);
0936:                            newlyCreated = true;
0937:                        } finally {
0938:                            if (!newlyCreated) {
0939:                                // object cannot be created
0940:                                _numActive--;
0941:                                notifyAll();
0942:                            }
0943:                        }
0944:                    }
0945:
0946:                    // activate & validate the object
0947:                    try {
0948:                        _factory.activateObject(pair.value);
0949:                        if (_testOnBorrow
0950:                                && !_factory.validateObject(pair.value)) {
0951:                            throw new Exception("ValidateObject failed");
0952:                        }
0953:                        return pair.value;
0954:                    } catch (Throwable e) {
0955:                        // object cannot be activated or is invalid
0956:                        _numActive--;
0957:                        notifyAll();
0958:                        try {
0959:                            _factory.destroyObject(pair.value);
0960:                        } catch (Throwable e2) {
0961:                            // cannot destroy broken object
0962:                        }
0963:                        if (newlyCreated) {
0964:                            throw new NoSuchElementException(
0965:                                    "Could not create a validated object, cause: "
0966:                                            + e.getMessage());
0967:                        } else {
0968:                            continue; // keep looping
0969:                        }
0970:                    }
0971:                }
0972:            }
0973:
0974:            public synchronized void invalidateObject(Object obj)
0975:                    throws Exception {
0976:                assertOpen();
0977:                try {
0978:                    _factory.destroyObject(obj);
0979:                } finally {
0980:                    _numActive--;
0981:                    notifyAll(); // _numActive has changed
0982:                }
0983:            }
0984:
0985:            public synchronized void clear() {
0986:                assertOpen();
0987:                for (Iterator it = _pool.iterator(); it.hasNext();) {
0988:                    try {
0989:                        _factory.destroyObject(((ObjectTimestampPair) (it
0990:                                .next())).value);
0991:                    } catch (Exception e) {
0992:                        // ignore error, keep destroying the rest
0993:                    }
0994:                    it.remove();
0995:                }
0996:                _pool.clear();
0997:                notifyAll(); // num sleeping has changed
0998:            }
0999:
1000:            public synchronized int getNumActive() {
1001:                assertOpen();
1002:                return _numActive;
1003:            }
1004:
1005:            public synchronized int getNumIdle() {
1006:                assertOpen();
1007:                return _pool.size();
1008:            }
1009:
1010:            public synchronized void returnObject(Object obj) throws Exception {
1011:                assertOpen();
1012:                addObjectToPool(obj, true);
1013:            }
1014:
1015:            private void addObjectToPool(Object obj, boolean decrementNumActive)
1016:                    throws Exception {
1017:                boolean success = true;
1018:                if (_testOnReturn && !(_factory.validateObject(obj))) {
1019:                    success = false;
1020:                } else {
1021:                    try {
1022:                        _factory.passivateObject(obj);
1023:                    } catch (Exception e) {
1024:                        success = false;
1025:                    }
1026:                }
1027:
1028:                boolean shouldDestroy = !success;
1029:
1030:                if (decrementNumActive) {
1031:                    _numActive--;
1032:                }
1033:                if ((_maxIdle >= 0) && (_pool.size() >= _maxIdle)) {
1034:                    shouldDestroy = true;
1035:                } else if (success) {
1036:                    _pool.addLast(new ObjectTimestampPair(obj));
1037:                }
1038:                notifyAll(); // _numActive has changed
1039:
1040:                if (shouldDestroy) {
1041:                    try {
1042:                        _factory.destroyObject(obj);
1043:                    } catch (Exception e) {
1044:                        // ignored
1045:                    }
1046:                }
1047:            }
1048:
1049:            public synchronized void close() throws Exception {
1050:                clear();
1051:                _pool = null;
1052:                _factory = null;
1053:                startEvictor(-1L);
1054:                super .close();
1055:            }
1056:
1057:            public synchronized void setFactory(PoolableObjectFactory factory)
1058:                    throws IllegalStateException {
1059:                assertOpen();
1060:                if (0 < getNumActive()) {
1061:                    throw new IllegalStateException(
1062:                            "Objects are already active");
1063:                } else {
1064:                    clear();
1065:                    _factory = factory;
1066:                }
1067:            }
1068:
1069:            public synchronized void evict() throws Exception {
1070:                assertOpen();
1071:                if (!_pool.isEmpty()) {
1072:                    ListIterator iter;
1073:                    if (evictLastIndex < 0) {
1074:                        iter = _pool.listIterator(_pool.size());
1075:                    } else {
1076:                        iter = _pool.listIterator(evictLastIndex);
1077:                    }
1078:                    for (int i = 0, m = getNumTests(); i < m; i++) {
1079:                        if (!iter.hasPrevious()) {
1080:                            iter = _pool.listIterator(_pool.size());
1081:                        }
1082:                        boolean removeObject = false;
1083:                        final ObjectTimestampPair pair = (ObjectTimestampPair) (iter
1084:                                .previous());
1085:                        final long idleTimeMilis = System.currentTimeMillis()
1086:                                - pair.tstamp;
1087:                        if ((_minEvictableIdleTimeMillis > 0)
1088:                                && (idleTimeMilis > _minEvictableIdleTimeMillis)) {
1089:                            removeObject = true;
1090:                        } else if ((_softMinEvictableIdleTimeMillis > 0)
1091:                                && (idleTimeMilis > _softMinEvictableIdleTimeMillis)
1092:                                && (getNumIdle() > getMinIdle())) {
1093:                            removeObject = true;
1094:                        }
1095:                        if (_testWhileIdle && !removeObject) {
1096:                            boolean active = false;
1097:                            try {
1098:                                _factory.activateObject(pair.value);
1099:                                active = true;
1100:                            } catch (Exception e) {
1101:                                removeObject = true;
1102:                            }
1103:                            if (active) {
1104:                                if (!_factory.validateObject(pair.value)) {
1105:                                    removeObject = true;
1106:                                } else {
1107:                                    try {
1108:                                        _factory.passivateObject(pair.value);
1109:                                    } catch (Exception e) {
1110:                                        removeObject = true;
1111:                                    }
1112:                                }
1113:                            }
1114:                        }
1115:                        if (removeObject) {
1116:                            try {
1117:                                iter.remove();
1118:                                _factory.destroyObject(pair.value);
1119:                            } catch (Exception e) {
1120:                                // ignored
1121:                            }
1122:                        }
1123:                    }
1124:                    evictLastIndex = iter.previousIndex(); // resume from here
1125:                } // if !empty
1126:            }
1127:
1128:            /**
1129:             * Check to see if we are below our minimum number of objects
1130:             * if so enough to bring us back to our minimum.
1131:             */
1132:            private void ensureMinIdle() throws Exception {
1133:                // this method isn't synchronized so the
1134:                // calculateDeficit is done at the beginning
1135:                // as a loop limit and a second time inside the loop
1136:                // to stop when another thread already returned the
1137:                // needed objects
1138:                int objectDeficit = calculateDeficit();
1139:                for (int j = 0; j < objectDeficit && calculateDeficit() > 0; j++) {
1140:                    addObject();
1141:                }
1142:            }
1143:
1144:            private synchronized int calculateDeficit() {
1145:                int objectDeficit = getMinIdle() - getNumIdle();
1146:                if (_maxActive > 0) {
1147:                    int growLimit = Math.max(0, getMaxActive() - getNumActive()
1148:                            - getNumIdle());
1149:                    objectDeficit = Math.min(objectDeficit, growLimit);
1150:                }
1151:                return objectDeficit;
1152:            }
1153:
1154:            /**
1155:             * Create an object, and place it into the pool.
1156:             * addObject() is useful for "pre-loading" a pool with idle objects.
1157:             */
1158:            public synchronized void addObject() throws Exception {
1159:                assertOpen();
1160:                Object obj = _factory.makeObject();
1161:                addObjectToPool(obj, false);
1162:            }
1163:
1164:            //--- non-public methods ----------------------------------------
1165:
1166:            /**
1167:             * Start the eviction thread or service, or when
1168:             * <i>delay</i> is non-positive, stop it
1169:             * if it is already running.
1170:             */
1171:            protected synchronized void startEvictor(long delay) {
1172:                if (null != _evictor) {
1173:                    _evictor.cancel();
1174:                    _evictor = null;
1175:                }
1176:                if (delay > 0) {
1177:                    _evictor = new Evictor();
1178:                    EVICTION_TIMER.schedule(_evictor, delay, delay);
1179:                }
1180:            }
1181:
1182:            synchronized String debugInfo() {
1183:                StringBuffer buf = new StringBuffer();
1184:                buf.append("Active: ").append(getNumActive()).append("\n");
1185:                buf.append("Idle: ").append(getNumIdle()).append("\n");
1186:                buf.append("Idle Objects:\n");
1187:                Iterator it = _pool.iterator();
1188:                long time = System.currentTimeMillis();
1189:                while (it.hasNext()) {
1190:                    ObjectTimestampPair pair = (ObjectTimestampPair) (it.next());
1191:                    buf.append("\t").append(pair.value).append("\t").append(
1192:                            time - pair.tstamp).append("\n");
1193:                }
1194:                return buf.toString();
1195:            }
1196:
1197:            private int getNumTests() {
1198:                if (_numTestsPerEvictionRun >= 0) {
1199:                    return Math.min(_numTestsPerEvictionRun, _pool.size());
1200:                } else {
1201:                    return (int) (Math.ceil((double) _pool.size()
1202:                            / Math.abs((double) _numTestsPerEvictionRun)));
1203:                }
1204:            }
1205:
1206:            //--- inner classes ----------------------------------------------
1207:
1208:            /**
1209:             * The idle object evictor {@link TimerTask}.
1210:             * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis
1211:             */
1212:            private class Evictor extends TimerTask {
1213:                public void run() {
1214:                    try {
1215:                        evict();
1216:                    } catch (Exception e) {
1217:                        // ignored
1218:                    }
1219:                    try {
1220:                        ensureMinIdle();
1221:                    } catch (Exception e) {
1222:                        // ignored
1223:                    }
1224:                }
1225:            }
1226:
1227:            /**
1228:             * A simple "struct" encapsulating the
1229:             * configuration information for a {@link GenericObjectPool}.
1230:             * @see GenericObjectPool#GenericObjectPool(org.apache.commons.pool.PoolableObjectFactory,org.apache.commons.pool.impl.GenericObjectPool.Config)
1231:             * @see GenericObjectPool#setConfig
1232:             */
1233:            public static class Config {
1234:                public int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE;
1235:                public int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE;
1236:                public int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE;
1237:                public long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT;
1238:                public byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
1239:                public boolean testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
1240:                public boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
1241:                public boolean testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
1242:                public long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
1243:                public int numTestsPerEvictionRun = GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
1244:                public long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1245:                public long softMinEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1246:            }
1247:
1248:            //--- private attributes ---------------------------------------
1249:
1250:            /**
1251:             * The cap on the number of idle instances in the pool.
1252:             * @see #setMaxIdle
1253:             * @see #getMaxIdle
1254:             */
1255:            private int _maxIdle = DEFAULT_MAX_IDLE;
1256:
1257:            /**
1258:             * The cap on the minimum number of idle instances in the pool.
1259:             * @see #setMinIdle
1260:             * @see #getMinIdle
1261:             */
1262:            private int _minIdle = DEFAULT_MIN_IDLE;
1263:
1264:            /**
1265:             * The cap on the total number of active instances from the pool.
1266:             * @see #setMaxActive
1267:             * @see #getMaxActive
1268:             */
1269:            protected int _maxActive = DEFAULT_MAX_ACTIVE;
1270:
1271:            /**
1272:             * The maximum amount of time (in millis) the
1273:             * {@link #borrowObject} method should block before throwing
1274:             * an exception when the pool is exhausted and the
1275:             * {@link #getWhenExhaustedAction "when exhausted" action} is
1276:             * {@link #WHEN_EXHAUSTED_BLOCK}.
1277:             *
1278:             * When less than 0, the {@link #borrowObject} method
1279:             * may block indefinitely.
1280:             *
1281:             * @see #setMaxWait
1282:             * @see #getMaxWait
1283:             * @see #WHEN_EXHAUSTED_BLOCK
1284:             * @see #setWhenExhaustedAction
1285:             * @see #getWhenExhaustedAction
1286:             */
1287:            protected long _maxWait = DEFAULT_MAX_WAIT;
1288:
1289:            /**
1290:             * The action to take when the {@link #borrowObject} method
1291:             * is invoked when the pool is exhausted (the maximum number
1292:             * of "active" objects has been reached).
1293:             *
1294:             * @see #WHEN_EXHAUSTED_BLOCK
1295:             * @see #WHEN_EXHAUSTED_FAIL
1296:             * @see #WHEN_EXHAUSTED_GROW
1297:             * @see #DEFAULT_WHEN_EXHAUSTED_ACTION
1298:             * @see #setWhenExhaustedAction
1299:             * @see #getWhenExhaustedAction
1300:             */
1301:            protected byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION;
1302:
1303:            /**
1304:             * When <tt>true</tt>, objects will be
1305:             * {@link PoolableObjectFactory#validateObject validated}
1306:             * before being returned by the {@link #borrowObject}
1307:             * method.  If the object fails to validate,
1308:             * it will be dropped from the pool, and we will attempt
1309:             * to borrow another.
1310:             *
1311:             * @see #setTestOnBorrow
1312:             * @see #getTestOnBorrow
1313:             */
1314:            protected boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW;
1315:
1316:            /**
1317:             * When <tt>true</tt>, objects will be
1318:             * {@link PoolableObjectFactory#validateObject validated}
1319:             * before being returned to the pool within the
1320:             * {@link #returnObject}.
1321:             *
1322:             * @see #getTestOnReturn
1323:             * @see #setTestOnReturn
1324:             */
1325:            private boolean _testOnReturn = DEFAULT_TEST_ON_RETURN;
1326:
1327:            /**
1328:             * When <tt>true</tt>, objects will be
1329:             * {@link PoolableObjectFactory#validateObject validated}
1330:             * by the idle object evictor (if any).  If an object
1331:             * fails to validate, it will be dropped from the pool.
1332:             *
1333:             * @see #setTestWhileIdle
1334:             * @see #getTestWhileIdle
1335:             * @see #getTimeBetweenEvictionRunsMillis
1336:             * @see #setTimeBetweenEvictionRunsMillis
1337:             */
1338:            private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE;
1339:
1340:            /**
1341:             * The number of milliseconds to sleep between runs of the
1342:             * idle object evictor thread.
1343:             * When non-positive, no idle object evictor thread will be
1344:             * run.
1345:             *
1346:             * @see #setTimeBetweenEvictionRunsMillis
1347:             * @see #getTimeBetweenEvictionRunsMillis
1348:             */
1349:            private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
1350:
1351:            /**
1352:             * The max number of objects to examine during each run of the
1353:             * idle object evictor thread (if any).
1354:             * <p>
1355:             * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
1356:             * tests will be run.  I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
1357:             * idle objects will be tested per run.
1358:             *
1359:             * @see #setNumTestsPerEvictionRun
1360:             * @see #getNumTestsPerEvictionRun
1361:             * @see #getTimeBetweenEvictionRunsMillis
1362:             * @see #setTimeBetweenEvictionRunsMillis
1363:             */
1364:            private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
1365:
1366:            /**
1367:             * The minimum amount of time an object may sit idle in the pool
1368:             * before it is eligable for eviction by the idle object evictor
1369:             * (if any).
1370:             * When non-positive, no objects will be evicted from the pool
1371:             * due to idle time alone.
1372:             *
1373:             * @see #setMinEvictableIdleTimeMillis
1374:             * @see #getMinEvictableIdleTimeMillis
1375:             * @see #getTimeBetweenEvictionRunsMillis
1376:             * @see #setTimeBetweenEvictionRunsMillis
1377:             */
1378:            private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1379:
1380:            /**
1381:             * The minimum amount of time an object may sit idle in the pool
1382:             * before it is eligable for eviction by the idle object evictor
1383:             * (if any), with the extra condition that at least
1384:             * "minIdle" amount of object remain in the pool.
1385:             * When non-positive, no objects will be evicted from the pool
1386:             * due to idle time alone.
1387:             *
1388:             * @see #setSoftMinEvictableIdleTimeMillis
1389:             * @see #getSoftMinEvictableIdleTimeMillis
1390:             */
1391:            private long _softMinEvictableIdleTimeMillis = DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
1392:
1393:            /** My pool. */
1394:            protected LinkedList _pool = null;
1395:
1396:            /** My {@link PoolableObjectFactory}. */
1397:            protected PoolableObjectFactory _factory = null;
1398:
1399:            /**
1400:             * The number of objects {@link #borrowObject} borrowed
1401:             * from the pool, but not yet returned.
1402:             */
1403:            protected int _numActive = 0;
1404:
1405:            /**
1406:             * My idle object eviction {@link TimerTask}, if any.
1407:             */
1408:            private Evictor _evictor = null;
1409:
1410:            /**
1411:             * Position in the _pool where the _evictor last stopped.
1412:             */
1413:            private int evictLastIndex = -1;
1414:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.