1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.pool.impl;
  17. import java.util.Iterator;
  18. import java.util.NoSuchElementException;
  19. import org.apache.commons.collections.CursorableLinkedList;
  20. import org.apache.commons.pool.BaseObjectPool;
  21. import org.apache.commons.pool.ObjectPool;
  22. import org.apache.commons.pool.PoolableObjectFactory;
  23. /**
  24. * A configurable {@link ObjectPool} implementation.
  25. * <p>
  26. * When coupled with the appropriate {@link PoolableObjectFactory},
  27. * <tt>GenericObjectPool</tt> provides robust pooling functionality for
  28. * arbitrary objects.
  29. * <p>
  30. * A <tt>GenericObjectPool</tt> provides a number of configurable parameters:
  31. * <ul>
  32. * <li>
  33. * {@link #setMaxActive <i>maxActive</i>} controls the maximum number of objects that can
  34. * be borrowed from the pool at one time. When non-positive, there
  35. * is no limit to the number of objects that may be active at one time.
  36. * When {@link #setMaxActive <i>maxActive</i>} is exceeded, the pool is said to be exhausted.
  37. * </li>
  38. * <li>
  39. * {@link #setMaxIdle <i>maxIdle</i>} controls the maximum number of objects that can
  40. * sit idle in the pool at any time. When negative, there
  41. * is no limit to the number of objects that may be idle at one time.
  42. * </li>
  43. * <li>
  44. * {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} specifies the
  45. * behaviour of the {@link #borrowObject} method when the pool is exhausted:
  46. * <ul>
  47. * <li>
  48. * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
  49. * {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject} will throw
  50. * a {@link NoSuchElementException}
  51. * </li>
  52. * <li>
  53. * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>} is
  54. * {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject} will create a new
  55. * object and return it(essentially making {@link #setMaxActive <i>maxActive</i>}
  56. * meaningless.)
  57. * </li>
  58. * <li>
  59. * When {@link #setWhenExhaustedAction <i>whenExhaustedAction</i>}
  60. * is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject} will block
  61. * (invoke {@link Object#wait} until a new or idle object is available.
  62. * If a positive {@link #setMaxWait <i>maxWait</i>}
  63. * value is supplied, the {@link #borrowObject} will block for at
  64. * most that many milliseconds, after which a {@link NoSuchElementException}
  65. * will be thrown. If {@link #setMaxWait <i>maxWait</i>} is non-positive,
  66. * the {@link #borrowObject} method will block indefinitely.
  67. * </li>
  68. * </ul>
  69. * </li>
  70. * <li>
  71. * When {@link #setTestOnBorrow <i>testOnBorrow</i>} is set, the pool will
  72. * attempt to validate each object before it is returned from the
  73. * {@link #borrowObject} method. (Using the provided factory's
  74. * {@link PoolableObjectFactory#validateObject} method.) Objects that fail
  75. * to validate will be dropped from the pool, and a different object will
  76. * be borrowed.
  77. * </li>
  78. * <li>
  79. * When {@link #setTestOnReturn <i>testOnReturn</i>} is set, the pool will
  80. * attempt to validate each object before it is returned to the pool in the
  81. * {@link #returnObject} method. (Using the provided factory's
  82. * {@link PoolableObjectFactory#validateObject}
  83. * method.) Objects that fail to validate will be dropped from the pool.
  84. * </li>
  85. * </ul>
  86. * <p>
  87. * Optionally, one may configure the pool to examine and possibly evict objects as they
  88. * sit idle in the pool. This is performed by an "idle object eviction" thread, which
  89. * runs asychronously. The idle object eviction thread may be configured using the
  90. * following attributes:
  91. * <ul>
  92. * <li>
  93. * {@link #setTimeBetweenEvictionRunsMillis <i>timeBetweenEvictionRunsMillis</i>}
  94. * indicates how long the eviction thread should sleep before "runs" of examining
  95. * idle objects. When non-positive, no eviction thread will be launched.
  96. * </li>
  97. * <li>
  98. * {@link #setMinEvictableIdleTimeMillis <i>minEvictableIdleTimeMillis</i>}
  99. * specifies the minimum amount of time that an object may sit idle in the pool
  100. * before it is eligable for eviction due to idle time. When non-positive, no object
  101. * will be dropped from the pool due to idle time alone.
  102. * </li>
  103. * <li>
  104. * {@link #setTestWhileIdle <i>testWhileIdle</i>} indicates whether or not idle
  105. * objects should be validated using the factory's
  106. * {@link PoolableObjectFactory#validateObject} method. Objects
  107. * that fail to validate will be dropped from the pool.
  108. * </li>
  109. * </ul>
  110. * <p>
  111. * GenericObjectPool is not usable without a {@link PoolableObjectFactory}. A
  112. * non-<code>null</code> factory must be provided either as a constructor argument
  113. * or via a call to {@link #setFactory} before the pool is used.
  114. *
  115. * @see GenericKeyedObjectPool
  116. * @author Rodney Waldhoff
  117. * @author Dirk Verbeeck
  118. * @version $Revision: 1.32 $ $Date: 2004/04/27 20:15:56 $
  119. */
  120. public class GenericObjectPool extends BaseObjectPool implements ObjectPool {
  121. //--- public constants -------------------------------------------
  122. /**
  123. * A "when exhausted action" type indicating that when the pool is
  124. * exhausted (i.e., the maximum number of active objects has
  125. * been reached), the {@link #borrowObject}
  126. * method should fail, throwing a {@link NoSuchElementException}.
  127. * @see #WHEN_EXHAUSTED_BLOCK
  128. * @see #WHEN_EXHAUSTED_GROW
  129. * @see #setWhenExhaustedAction
  130. */
  131. public static final byte WHEN_EXHAUSTED_FAIL = 0;
  132. /**
  133. * A "when exhausted action" type indicating that when the pool
  134. * is exhausted (i.e., the maximum number
  135. * of active objects has been reached), the {@link #borrowObject}
  136. * method should block until a new object is available, or the
  137. * {@link #getMaxWait maximum wait time} has been reached.
  138. * @see #WHEN_EXHAUSTED_FAIL
  139. * @see #WHEN_EXHAUSTED_GROW
  140. * @see #setMaxWait
  141. * @see #getMaxWait
  142. * @see #setWhenExhaustedAction
  143. */
  144. public static final byte WHEN_EXHAUSTED_BLOCK = 1;
  145. /**
  146. * A "when exhausted action" type indicating that when the pool is
  147. * exhausted (i.e., the maximum number
  148. * of active objects has been reached), the {@link #borrowObject}
  149. * method should simply create a new object anyway.
  150. * @see #WHEN_EXHAUSTED_FAIL
  151. * @see #WHEN_EXHAUSTED_GROW
  152. * @see #setWhenExhaustedAction
  153. */
  154. public static final byte WHEN_EXHAUSTED_GROW = 2;
  155. /**
  156. * The default cap on the number of "sleeping" instances in the pool.
  157. * @see #getMaxIdle
  158. * @see #setMaxIdle
  159. */
  160. public static final int DEFAULT_MAX_IDLE = 8;
  161. /**
  162. * The default minimum number of "sleeping" instances in the pool
  163. * before before the evictor thread (if active) spawns new objects.
  164. * @see #getMinIdle
  165. * @see #setMinIdle
  166. */
  167. public static final int DEFAULT_MIN_IDLE = 0;
  168. /**
  169. * The default cap on the total number of active instances from the pool.
  170. * @see #getMaxActive
  171. */
  172. public static final int DEFAULT_MAX_ACTIVE = 8;
  173. /**
  174. * The default "when exhausted action" for the pool.
  175. * @see #WHEN_EXHAUSTED_BLOCK
  176. * @see #WHEN_EXHAUSTED_FAIL
  177. * @see #WHEN_EXHAUSTED_GROW
  178. * @see #setWhenExhaustedAction
  179. */
  180. public static final byte DEFAULT_WHEN_EXHAUSTED_ACTION = WHEN_EXHAUSTED_BLOCK;
  181. /**
  182. * The default maximum amount of time (in millis) the
  183. * {@link #borrowObject} method should block before throwing
  184. * an exception when the pool is exhausted and the
  185. * {@link #getWhenExhaustedAction "when exhausted" action} is
  186. * {@link #WHEN_EXHAUSTED_BLOCK}.
  187. * @see #getMaxWait
  188. * @see #setMaxWait
  189. */
  190. public static final long DEFAULT_MAX_WAIT = -1L;
  191. /**
  192. * The default "test on borrow" value.
  193. * @see #getTestOnBorrow
  194. * @see #setTestOnBorrow
  195. */
  196. public static final boolean DEFAULT_TEST_ON_BORROW = false;
  197. /**
  198. * The default "test on return" value.
  199. * @see #getTestOnReturn
  200. * @see #setTestOnReturn
  201. */
  202. public static final boolean DEFAULT_TEST_ON_RETURN = false;
  203. /**
  204. * The default "test while idle" value.
  205. * @see #getTestWhileIdle
  206. * @see #setTestWhileIdle
  207. * @see #getTimeBetweenEvictionRunsMillis
  208. * @see #setTimeBetweenEvictionRunsMillis
  209. */
  210. public static final boolean DEFAULT_TEST_WHILE_IDLE = false;
  211. /**
  212. * The default "time between eviction runs" value.
  213. * @see #getTimeBetweenEvictionRunsMillis
  214. * @see #setTimeBetweenEvictionRunsMillis
  215. */
  216. public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L;
  217. /**
  218. * The default number of objects to examine per run in the
  219. * idle object evictor.
  220. * @see #getNumTestsPerEvictionRun
  221. * @see #setNumTestsPerEvictionRun
  222. * @see #getTimeBetweenEvictionRunsMillis
  223. * @see #setTimeBetweenEvictionRunsMillis
  224. */
  225. public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3;
  226. /**
  227. * The default value for {@link #getMinEvictableIdleTimeMillis}.
  228. * @see #getMinEvictableIdleTimeMillis
  229. * @see #setMinEvictableIdleTimeMillis
  230. */
  231. public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L;
  232. //--- constructors -----------------------------------------------
  233. /**
  234. * Create a new <tt>GenericObjectPool</tt>.
  235. */
  236. public GenericObjectPool() {
  237. this(null,DEFAULT_MAX_ACTIVE,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
  238. }
  239. /**
  240. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  241. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  242. */
  243. public GenericObjectPool(PoolableObjectFactory factory) {
  244. this(factory,DEFAULT_MAX_ACTIVE,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
  245. }
  246. /**
  247. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  248. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  249. * @param config a non-<tt>null</tt> {@link GenericObjectPool.Config} describing my configuration
  250. */
  251. public GenericObjectPool(PoolableObjectFactory factory, GenericObjectPool.Config config) {
  252. this(factory,config.maxActive,config.whenExhaustedAction,config.maxWait,config.maxIdle,config.minIdle,config.testOnBorrow,config.testOnReturn,config.timeBetweenEvictionRunsMillis,config.numTestsPerEvictionRun,config.minEvictableIdleTimeMillis,config.testWhileIdle);
  253. }
  254. /**
  255. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  256. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  257. * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
  258. */
  259. public GenericObjectPool(PoolableObjectFactory factory, int maxActive) {
  260. this(factory,maxActive,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
  261. }
  262. /**
  263. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  264. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  265. * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
  266. * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
  267. * @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})
  268. */
  269. public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait) {
  270. this(factory,maxActive,whenExhaustedAction,maxWait,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
  271. }
  272. /**
  273. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  274. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  275. * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
  276. * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
  277. * @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})
  278. * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #getTestOnBorrow})
  279. * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #getTestOnReturn})
  280. */
  281. public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, boolean testOnBorrow, boolean testOnReturn) {
  282. this(factory,maxActive,whenExhaustedAction,maxWait,DEFAULT_MAX_IDLE,DEFAULT_MIN_IDLE,testOnBorrow,testOnReturn,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
  283. }
  284. /**
  285. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  286. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  287. * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
  288. * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
  289. * @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})
  290. * @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle})
  291. */
  292. public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle) {
  293. this(factory,maxActive,whenExhaustedAction,maxWait,maxIdle,DEFAULT_MIN_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
  294. }
  295. /**
  296. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  297. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  298. * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
  299. * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
  300. * @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})
  301. * @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle})
  302. * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #getTestOnBorrow})
  303. * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #getTestOnReturn})
  304. */
  305. public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn) {
  306. this(factory,maxActive,whenExhaustedAction,maxWait,maxIdle,DEFAULT_MIN_IDLE,testOnBorrow,testOnReturn,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
  307. }
  308. /**
  309. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  310. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  311. * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
  312. * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
  313. * @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})
  314. * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
  315. * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
  316. * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
  317. * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
  318. * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
  319. * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligable for evcition (see {@link #setMinEvictableIdleTimeMillis})
  320. * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
  321. */
  322. public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) {
  323. this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle);
  324. }
  325. /**
  326. * Create a new <tt>GenericObjectPool</tt> using the specified values.
  327. * @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
  328. * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
  329. * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
  330. * @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})
  331. * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
  332. * @param minIdle the minimum number of idle objects in my pool (see {@link #setMinIdle})
  333. * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
  334. * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
  335. * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
  336. * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
  337. * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligable for evcition (see {@link #setMinEvictableIdleTimeMillis})
  338. * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
  339. */
  340. public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, int minIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) {
  341. _factory = factory;
  342. _maxActive = maxActive;
  343. switch(whenExhaustedAction) {
  344. case WHEN_EXHAUSTED_BLOCK:
  345. case WHEN_EXHAUSTED_FAIL:
  346. case WHEN_EXHAUSTED_GROW:
  347. _whenExhaustedAction = whenExhaustedAction;
  348. break;
  349. default:
  350. throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
  351. }
  352. _maxWait = maxWait;
  353. _maxIdle = maxIdle;
  354. _minIdle = minIdle;
  355. _testOnBorrow = testOnBorrow;
  356. _testOnReturn = testOnReturn;
  357. _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  358. _numTestsPerEvictionRun = numTestsPerEvictionRun;
  359. _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  360. _testWhileIdle = testWhileIdle;
  361. _pool = new CursorableLinkedList();
  362. startEvictor(_timeBetweenEvictionRunsMillis);
  363. }
  364. //--- public methods ---------------------------------------------
  365. //--- configuration methods --------------------------------------
  366. /**
  367. * Returns the cap on the total number of active instances from my pool.
  368. * @return the cap on the total number of active instances from my pool.
  369. * @see #setMaxActive
  370. */
  371. public synchronized int getMaxActive() {
  372. return _maxActive;
  373. }
  374. /**
  375. * Sets the cap on the total number of active instances from my pool.
  376. * @param maxActive The cap on the total number of active instances from my pool.
  377. * Use a negative value for an infinite number of instances.
  378. * @see #getMaxActive
  379. */
  380. public synchronized void setMaxActive(int maxActive) {
  381. _maxActive = maxActive;
  382. notifyAll();
  383. }
  384. /**
  385. * Returns the action to take when the {@link #borrowObject} method
  386. * is invoked when the pool is exhausted (the maximum number
  387. * of "active" objects has been reached).
  388. *
  389. * @return one of {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW}
  390. * @see #setWhenExhaustedAction
  391. */
  392. public synchronized byte getWhenExhaustedAction() {
  393. return _whenExhaustedAction;
  394. }
  395. /**
  396. * Sets the action to take when the {@link #borrowObject} method
  397. * is invoked when the pool is exhausted (the maximum number
  398. * of "active" objects has been reached).
  399. *
  400. * @param whenExhaustedAction the action code, which must be one of
  401. * {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL},
  402. * or {@link #WHEN_EXHAUSTED_GROW}
  403. * @see #getWhenExhaustedAction
  404. */
  405. public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) {
  406. switch(whenExhaustedAction) {
  407. case WHEN_EXHAUSTED_BLOCK:
  408. case WHEN_EXHAUSTED_FAIL:
  409. case WHEN_EXHAUSTED_GROW:
  410. _whenExhaustedAction = whenExhaustedAction;
  411. notifyAll();
  412. break;
  413. default:
  414. throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
  415. }
  416. }
  417. /**
  418. * Returns the maximum amount of time (in milliseconds) the
  419. * {@link #borrowObject} method should block before throwing
  420. * an exception when the pool is exhausted and the
  421. * {@link #setWhenExhaustedAction "when exhausted" action} is
  422. * {@link #WHEN_EXHAUSTED_BLOCK}.
  423. *
  424. * When less than 0, the {@link #borrowObject} method
  425. * may block indefinitely.
  426. *
  427. * @see #setMaxWait
  428. * @see #setWhenExhaustedAction
  429. * @see #WHEN_EXHAUSTED_BLOCK
  430. */
  431. public synchronized long getMaxWait() {
  432. return _maxWait;
  433. }
  434. /**
  435. * Sets the maximum amount of time (in milliseconds) the
  436. * {@link #borrowObject} method should block before throwing
  437. * an exception when the pool is exhausted and the
  438. * {@link #setWhenExhaustedAction "when exhausted" action} is
  439. * {@link #WHEN_EXHAUSTED_BLOCK}.
  440. *
  441. * When less than 0, the {@link #borrowObject} method
  442. * may block indefinitely.
  443. *
  444. * @see #getMaxWait
  445. * @see #setWhenExhaustedAction
  446. * @see #WHEN_EXHAUSTED_BLOCK
  447. */
  448. public synchronized void setMaxWait(long maxWait) {
  449. _maxWait = maxWait;
  450. notifyAll();
  451. }
  452. /**
  453. * Returns the cap on the number of "idle" instances in the pool.
  454. * @return the cap on the number of "idle" instances in the pool.
  455. * @see #setMaxIdle
  456. */
  457. public synchronized int getMaxIdle() {
  458. return _maxIdle;
  459. }
  460. /**
  461. * Sets the cap on the number of "idle" instances in the pool.
  462. * @param maxIdle The cap on the number of "idle" instances in the pool.
  463. * Use a negative value to indicate an unlimited number
  464. * of idle instances.
  465. * @see #getMaxIdle
  466. */
  467. public synchronized void setMaxIdle(int maxIdle) {
  468. _maxIdle = maxIdle;
  469. notifyAll();
  470. }
  471. /**
  472. * Sets the minimum number of objects allowed in the pool
  473. * before the evictor thread (if active) spawns new objects.
  474. * (Note no objects are created when: numActive + numIdle >= maxActive)
  475. *
  476. * @param minIdle The minimum number of objects.
  477. * @see #getMinIdle
  478. */
  479. public synchronized void setMinIdle(int minIdle) {
  480. _minIdle = minIdle;
  481. notifyAll();
  482. }
  483. /**
  484. * Returns the minimum number of objects allowed in the pool
  485. * before the evictor thread (if active) spawns new objects.
  486. * (Note no objects are created when: numActive + numIdle >= maxActive)
  487. *
  488. * @return The minimum number of objects.
  489. * @see #setMinIdle
  490. */
  491. public synchronized int getMinIdle() {
  492. return _minIdle;
  493. }
  494. /**
  495. * When <tt>true</tt>, objects will be
  496. * {@link PoolableObjectFactory#validateObject validated}
  497. * before being returned by the {@link #borrowObject}
  498. * method. If the object fails to validate,
  499. * it will be dropped from the pool, and we will attempt
  500. * to borrow another.
  501. *
  502. * @see #setTestOnBorrow
  503. */
  504. public synchronized boolean getTestOnBorrow() {
  505. return _testOnBorrow;
  506. }
  507. /**
  508. * When <tt>true</tt>, objects will be
  509. * {@link PoolableObjectFactory#validateObject validated}
  510. * before being returned by the {@link #borrowObject}
  511. * method. If the object fails to validate,
  512. * it will be dropped from the pool, and we will attempt
  513. * to borrow another.
  514. *
  515. * @see #getTestOnBorrow
  516. */
  517. public synchronized void setTestOnBorrow(boolean testOnBorrow) {
  518. _testOnBorrow = testOnBorrow;
  519. }
  520. /**
  521. * When <tt>true</tt>, objects will be
  522. * {@link PoolableObjectFactory#validateObject validated}
  523. * before being returned to the pool within the
  524. * {@link #returnObject}.
  525. *
  526. * @see #setTestOnReturn
  527. */
  528. public synchronized boolean getTestOnReturn() {
  529. return _testOnReturn;
  530. }
  531. /**
  532. * When <tt>true</tt>, objects will be
  533. * {@link PoolableObjectFactory#validateObject validated}
  534. * before being returned to the pool within the
  535. * {@link #returnObject}.
  536. *
  537. * @see #getTestOnReturn
  538. */
  539. public synchronized void setTestOnReturn(boolean testOnReturn) {
  540. _testOnReturn = testOnReturn;
  541. }
  542. /**
  543. * Returns the number of milliseconds to sleep between runs of the
  544. * idle object evictor thread.
  545. * When non-positive, no idle object evictor thread will be
  546. * run.
  547. *
  548. * @see #setTimeBetweenEvictionRunsMillis
  549. */
  550. public synchronized long getTimeBetweenEvictionRunsMillis() {
  551. return _timeBetweenEvictionRunsMillis;
  552. }
  553. /**
  554. * Sets the number of milliseconds to sleep between runs of the
  555. * idle object evictor thread.
  556. * When non-positive, no idle object evictor thread will be
  557. * run.
  558. *
  559. * @see #getTimeBetweenEvictionRunsMillis
  560. */
  561. public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
  562. _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  563. startEvictor(_timeBetweenEvictionRunsMillis);
  564. }
  565. /**
  566. * Returns the number of objects to examine during each run of the
  567. * idle object evictor thread (if any).
  568. *
  569. * @see #setNumTestsPerEvictionRun
  570. * @see #setTimeBetweenEvictionRunsMillis
  571. */
  572. public synchronized int getNumTestsPerEvictionRun() {
  573. return _numTestsPerEvictionRun;
  574. }
  575. /**
  576. * Sets the number of objects to examine during each run of the
  577. * idle object evictor thread (if any).
  578. * <p>
  579. * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
  580. * tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
  581. * idle objects will be tested per run.
  582. *
  583. * @see #getNumTestsPerEvictionRun
  584. * @see #setTimeBetweenEvictionRunsMillis
  585. */
  586. public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
  587. _numTestsPerEvictionRun = numTestsPerEvictionRun;
  588. }
  589. /**
  590. * Returns the minimum amount of time an object may sit idle in the pool
  591. * before it is eligable for eviction by the idle object evictor
  592. * (if any).
  593. *
  594. * @see #setMinEvictableIdleTimeMillis
  595. * @see #setTimeBetweenEvictionRunsMillis
  596. */
  597. public synchronized long getMinEvictableIdleTimeMillis() {
  598. return _minEvictableIdleTimeMillis;
  599. }
  600. /**
  601. * Sets the minimum amount of time an object may sit idle in the pool
  602. * before it is eligable for eviction by the idle object evictor
  603. * (if any).
  604. * When non-positive, no objects will be evicted from the pool
  605. * due to idle time alone.
  606. *
  607. * @see #getMinEvictableIdleTimeMillis
  608. * @see #setTimeBetweenEvictionRunsMillis
  609. */
  610. public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
  611. _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  612. }
  613. /**
  614. * When <tt>true</tt>, objects will be
  615. * {@link PoolableObjectFactory#validateObject validated}
  616. * by the idle object evictor (if any). If an object
  617. * fails to validate, it will be dropped from the pool.
  618. *
  619. * @see #setTestWhileIdle
  620. * @see #setTimeBetweenEvictionRunsMillis
  621. */
  622. public synchronized boolean getTestWhileIdle() {
  623. return _testWhileIdle;
  624. }
  625. /**
  626. * When <tt>true</tt>, objects will be
  627. * {@link PoolableObjectFactory#validateObject validated}
  628. * by the idle object evictor (if any). If an object
  629. * fails to validate, it will be dropped from the pool.
  630. *
  631. * @see #getTestWhileIdle
  632. * @see #setTimeBetweenEvictionRunsMillis
  633. */
  634. public synchronized void setTestWhileIdle(boolean testWhileIdle) {
  635. _testWhileIdle = testWhileIdle;
  636. }
  637. /**
  638. * Sets my configuration.
  639. * @see GenericObjectPool.Config
  640. */
  641. public synchronized void setConfig(GenericObjectPool.Config conf) {
  642. setMaxIdle(conf.maxIdle);
  643. setMinIdle(conf.minIdle);
  644. setMaxActive(conf.maxActive);
  645. setMaxWait(conf.maxWait);
  646. setWhenExhaustedAction(conf.whenExhaustedAction);
  647. setTestOnBorrow(conf.testOnBorrow);
  648. setTestOnReturn(conf.testOnReturn);
  649. setTestWhileIdle(conf.testWhileIdle);
  650. setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun);
  651. setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
  652. setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
  653. notifyAll();
  654. }
  655. //-- ObjectPool methods ------------------------------------------
  656. public Object borrowObject() throws Exception {
  657. long starttime = System.currentTimeMillis();
  658. boolean newlyCreated = false;
  659. for(;;) {
  660. ObjectTimestampPair pair = null;
  661. synchronized(this) {
  662. assertOpen();
  663. // if there are any sleeping, just grab one of those
  664. try {
  665. pair = (ObjectTimestampPair)(_pool.removeFirst());
  666. } catch(NoSuchElementException e) {
  667. ; /* ignored */
  668. }
  669. // otherwise
  670. if(null == pair) {
  671. // check if we can create one
  672. // (note we know that the num sleeping is 0, else we wouldn't be here)
  673. if(_maxActive <= 0 || _numActive < _maxActive) {
  674. // allow new object to be created
  675. } else {
  676. // the pool is exhausted
  677. switch(_whenExhaustedAction) {
  678. case WHEN_EXHAUSTED_GROW:
  679. // allow new object to be created
  680. break;
  681. case WHEN_EXHAUSTED_FAIL:
  682. throw new NoSuchElementException();
  683. case WHEN_EXHAUSTED_BLOCK:
  684. try {
  685. if(_maxWait <= 0) {
  686. wait();
  687. } else {
  688. wait(_maxWait);
  689. }
  690. } catch(InterruptedException e) {
  691. // ignored
  692. }
  693. if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
  694. throw new NoSuchElementException("Timeout waiting for idle object");
  695. } else {
  696. continue; // keep looping
  697. }
  698. default:
  699. throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized.");
  700. }
  701. }
  702. }
  703. _numActive++;
  704. } // end synchronized
  705. // create new object when needed
  706. if(null == pair) {
  707. try {
  708. Object obj = _factory.makeObject();
  709. pair = new ObjectTimestampPair(obj);
  710. newlyCreated = true;
  711. }
  712. catch (Exception e) {
  713. // object cannot be created
  714. synchronized(this) {
  715. _numActive--;
  716. notifyAll();
  717. }
  718. throw e;
  719. }
  720. }
  721. // activate & validate the object
  722. try {
  723. _factory.activateObject(pair.value);
  724. if(_testOnBorrow && !_factory.validateObject(pair.value)) {
  725. throw new Exception("validateObject failed");
  726. }
  727. return pair.value;
  728. }
  729. catch (Exception e) {
  730. // object cannot be activated or is invalid
  731. synchronized(this) {
  732. _numActive--;
  733. notifyAll();
  734. }
  735. try {
  736. _factory.destroyObject(pair.value);
  737. }
  738. catch (Exception e2) {
  739. // cannot destroy broken object
  740. }
  741. if(newlyCreated) {
  742. throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
  743. }
  744. else {
  745. continue; // keep looping
  746. }
  747. }
  748. }
  749. }
  750. public void invalidateObject(Object obj) throws Exception {
  751. assertOpen();
  752. try {
  753. _factory.destroyObject(obj);
  754. }
  755. finally {
  756. synchronized(this) {
  757. _numActive--;
  758. notifyAll(); // _numActive has changed
  759. }
  760. }
  761. }
  762. public synchronized void clear() {
  763. assertOpen();
  764. for(Iterator it = _pool.iterator(); it.hasNext(); ) {
  765. try {
  766. _factory.destroyObject(((ObjectTimestampPair)(it.next())).value);
  767. } catch(Exception e) {
  768. // ignore error, keep destroying the rest
  769. }
  770. it.remove();
  771. }
  772. _pool.clear();
  773. notifyAll(); // num sleeping has changed
  774. }
  775. public synchronized int getNumActive() {
  776. assertOpen();
  777. return _numActive;
  778. }
  779. public synchronized int getNumIdle() {
  780. assertOpen();
  781. return _pool.size();
  782. }
  783. public void returnObject(Object obj) throws Exception {
  784. assertOpen();
  785. addObjectToPool(obj, true);
  786. }
  787. private void addObjectToPool(Object obj, boolean decrementNumActive) throws Exception {
  788. boolean success = true;
  789. if(_testOnReturn && !(_factory.validateObject(obj))) {
  790. success = false;
  791. } else {
  792. try {
  793. _factory.passivateObject(obj);
  794. } catch(Exception e) {
  795. success = false;
  796. }
  797. }
  798. boolean shouldDestroy = !success;
  799. synchronized(this) {
  800. if (decrementNumActive) {
  801. _numActive--;
  802. }
  803. if((_maxIdle >= 0) && (_pool.size() >= _maxIdle)) {
  804. shouldDestroy = true;
  805. } else if(success) {
  806. _pool.addFirst(new ObjectTimestampPair(obj));
  807. }
  808. notifyAll(); // _numActive has changed
  809. }
  810. if(shouldDestroy) {
  811. try {
  812. _factory.destroyObject(obj);
  813. } catch(Exception e) {
  814. // ignored
  815. }
  816. }
  817. }
  818. public synchronized void close() throws Exception {
  819. clear();
  820. _pool = null;
  821. _factory = null;
  822. if(null != _evictionCursor) {
  823. _evictionCursor.close();
  824. _evictionCursor = null;
  825. }
  826. startEvictor(-1L);
  827. super.close();
  828. }
  829. public synchronized void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
  830. assertOpen();
  831. if(0 < getNumActive()) {
  832. throw new IllegalStateException("Objects are already active");
  833. } else {
  834. clear();
  835. _factory = factory;
  836. }
  837. }
  838. public synchronized void evict() throws Exception {
  839. assertOpen();
  840. if(!_pool.isEmpty()) {
  841. if(null == _evictionCursor) {
  842. _evictionCursor = (_pool.cursor(_pool.size()));
  843. } else if(!_evictionCursor.hasPrevious()) {
  844. _evictionCursor.close();
  845. _evictionCursor = (_pool.cursor(_pool.size()));
  846. }
  847. for(int i=0,m=getNumTests();i<m;i++) {
  848. if(!_evictionCursor.hasPrevious()) {
  849. _evictionCursor.close();
  850. _evictionCursor = (_pool.cursor(_pool.size()));
  851. } else {
  852. boolean removeObject = false;
  853. ObjectTimestampPair pair = (ObjectTimestampPair)(_evictionCursor.previous());
  854. if(_minEvictableIdleTimeMillis > 0 &&
  855. System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis) {
  856. removeObject = true;
  857. } else if(_testWhileIdle) {
  858. boolean active = false;
  859. try {
  860. _factory.activateObject(pair.value);
  861. active = true;
  862. } catch(Exception e) {
  863. removeObject=true;
  864. }
  865. if(active) {
  866. if(!_factory.validateObject(pair.value)) {
  867. removeObject=true;
  868. } else {
  869. try {
  870. _factory.passivateObject(pair.value);
  871. } catch(Exception e) {
  872. removeObject=true;
  873. }
  874. }
  875. }
  876. }
  877. if(removeObject) {
  878. try {
  879. _evictionCursor.remove();
  880. _factory.destroyObject(pair.value);
  881. } catch(Exception e) {
  882. ; // ignored
  883. }
  884. }
  885. }
  886. }
  887. } // if !empty
  888. }
  889. /**
  890. * Check to see if we are below our minimum number of objects
  891. * if so enough to bring us back to our minimum.
  892. */
  893. private void ensureMinIdle() throws Exception {
  894. // this method isn't synchronized so the
  895. // calculateDeficit is done at the beginning
  896. // as a loop limit and a second time inside the loop
  897. // to stop when another thread already returned the
  898. // needed objects
  899. int objectDeficit = calculateDeficit();
  900. for ( int j = 0 ; j < objectDeficit && calculateDeficit() > 0 ; j++ ) {
  901. addObject();
  902. }
  903. }
  904. private synchronized int calculateDeficit() {
  905. int objectDeficit = getMinIdle() - getNumIdle();
  906. if (_maxActive > 0) {
  907. int growLimit = Math.max(0, getMaxActive() - getNumActive() - getNumIdle());
  908. objectDeficit = Math.min(objectDeficit, growLimit);
  909. }
  910. return objectDeficit;
  911. }
  912. /**
  913. * Create an object, and place it into the pool.
  914. * addObject() is useful for "pre-loading" a pool with idle objects.
  915. */
  916. public void addObject() throws Exception {
  917. Object obj = _factory.makeObject();
  918. addObjectToPool(obj, false);
  919. }
  920. //--- non-public methods ----------------------------------------
  921. /**
  922. * Start the eviction thread or service, or when
  923. * <i>delay</i> is non-positive, stop it
  924. * if it is already running.
  925. */
  926. protected synchronized void startEvictor(long delay) {
  927. if(null != _evictor) {
  928. _evictor.cancel();
  929. _evictor = null;
  930. }
  931. if(delay > 0) {
  932. _evictor = new Evictor(delay);
  933. Thread t = new Thread(_evictor);
  934. t.setDaemon(true);
  935. t.start();
  936. }
  937. }
  938. synchronized String debugInfo() {
  939. StringBuffer buf = new StringBuffer();
  940. buf.append("Active: ").append(getNumActive()).append("\n");
  941. buf.append("Idle: ").append(getNumIdle()).append("\n");
  942. buf.append("Idle Objects:\n");
  943. Iterator it = _pool.iterator();
  944. long time = System.currentTimeMillis();
  945. while(it.hasNext()) {
  946. ObjectTimestampPair pair = (ObjectTimestampPair)(it.next());
  947. buf.append("\t").append(pair.value).append("\t").append(time - pair.tstamp).append("\n");
  948. }
  949. return buf.toString();
  950. }
  951. private int getNumTests() {
  952. if(_numTestsPerEvictionRun >= 0) {
  953. return _numTestsPerEvictionRun;
  954. } else {
  955. return(int)(Math.ceil((double)_pool.size()/Math.abs((double)_numTestsPerEvictionRun)));
  956. }
  957. }
  958. //--- inner classes ----------------------------------------------
  959. /**
  960. * A simple "struct" encapsulating an object instance and a timestamp.
  961. */
  962. class ObjectTimestampPair {
  963. Object value;
  964. long tstamp;
  965. ObjectTimestampPair(Object val) {
  966. this(val,System.currentTimeMillis());
  967. }
  968. ObjectTimestampPair(Object val, long time) {
  969. value = val;
  970. tstamp = time;
  971. }
  972. }
  973. /**
  974. * The idle object evictor thread.
  975. * @see #setTimeBetweenEvictionRunsMillis
  976. */
  977. class Evictor implements Runnable {
  978. private boolean _cancelled = false;
  979. private long _delay = 0L;
  980. public Evictor(long delay) {
  981. _delay = delay;
  982. }
  983. void cancel() {
  984. _cancelled = true;
  985. }
  986. public void run() {
  987. while(!_cancelled) {
  988. try {
  989. Thread.sleep(_delay);
  990. } catch(Exception e) {
  991. // ignored
  992. }
  993. try {
  994. evict();
  995. } catch(Exception e) {
  996. // ignored
  997. }
  998. try {
  999. ensureMinIdle();
  1000. } catch(Exception e) {
  1001. // ignored
  1002. }
  1003. }
  1004. synchronized(GenericObjectPool.this) {
  1005. if(null != _evictionCursor) {
  1006. _evictionCursor.close();
  1007. _evictionCursor = null;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. /**
  1013. * A simple "struct" encapsulating the
  1014. * configuration information for a {@link GenericObjectPool}.
  1015. * @see GenericObjectPool#GenericObjectPool(org.apache.commons.pool.PoolableObjectFactory,org.apache.commons.pool.impl.GenericObjectPool.Config)
  1016. * @see GenericObjectPool#setConfig
  1017. */
  1018. public static class Config {
  1019. public int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE;
  1020. public int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE;
  1021. public int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE;
  1022. public long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT;
  1023. public byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
  1024. public boolean testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
  1025. public boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
  1026. public boolean testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
  1027. public long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
  1028. public int numTestsPerEvictionRun = GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
  1029. public long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
  1030. }
  1031. //--- private attributes ---------------------------------------
  1032. /**
  1033. * The cap on the number of idle instances in the pool.
  1034. * @see #setMaxIdle
  1035. * @see #getMaxIdle
  1036. */
  1037. private int _maxIdle = DEFAULT_MAX_IDLE;
  1038. /**
  1039. * The cap on the minimum number of idle instances in the pool.
  1040. * @see #setMinIdle
  1041. * @see #getMinIdle
  1042. */
  1043. private int _minIdle = DEFAULT_MIN_IDLE;
  1044. /**
  1045. * The cap on the total number of active instances from the pool.
  1046. * @see #setMaxActive
  1047. * @see #getMaxActive
  1048. */
  1049. private int _maxActive = DEFAULT_MAX_ACTIVE;
  1050. /**
  1051. * The maximum amount of time (in millis) the
  1052. * {@link #borrowObject} method should block before throwing
  1053. * an exception when the pool is exhausted and the
  1054. * {@link #getWhenExhaustedAction "when exhausted" action} is
  1055. * {@link #WHEN_EXHAUSTED_BLOCK}.
  1056. *
  1057. * When less than 0, the {@link #borrowObject} method
  1058. * may block indefinitely.
  1059. *
  1060. * @see #setMaxWait
  1061. * @see #getMaxWait
  1062. * @see #WHEN_EXHAUSTED_BLOCK
  1063. * @see #setWhenExhaustedAction
  1064. * @see #getWhenExhaustedAction
  1065. */
  1066. private long _maxWait = DEFAULT_MAX_WAIT;
  1067. /**
  1068. * The action to take when the {@link #borrowObject} method
  1069. * is invoked when the pool is exhausted (the maximum number
  1070. * of "active" objects has been reached).
  1071. *
  1072. * @see #WHEN_EXHAUSTED_BLOCK
  1073. * @see #WHEN_EXHAUSTED_FAIL
  1074. * @see #WHEN_EXHAUSTED_GROW
  1075. * @see #DEFAULT_WHEN_EXHAUSTED_ACTION
  1076. * @see #setWhenExhaustedAction
  1077. * @see #getWhenExhaustedAction
  1078. */
  1079. private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION;
  1080. /**
  1081. * When <tt>true</tt>, objects will be
  1082. * {@link PoolableObjectFactory#validateObject validated}
  1083. * before being returned by the {@link #borrowObject}
  1084. * method. If the object fails to validate,
  1085. * it will be dropped from the pool, and we will attempt
  1086. * to borrow another.
  1087. *
  1088. * @see #setTestOnBorrow
  1089. * @see #getTestOnBorrow
  1090. */
  1091. private boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW;
  1092. /**
  1093. * When <tt>true</tt>, objects will be
  1094. * {@link PoolableObjectFactory#validateObject validated}
  1095. * before being returned to the pool within the
  1096. * {@link #returnObject}.
  1097. *
  1098. * @see #getTestOnReturn
  1099. * @see #setTestOnReturn
  1100. */
  1101. private boolean _testOnReturn = DEFAULT_TEST_ON_RETURN;
  1102. /**
  1103. * When <tt>true</tt>, objects will be
  1104. * {@link PoolableObjectFactory#validateObject validated}
  1105. * by the idle object evictor (if any). If an object
  1106. * fails to validate, it will be dropped from the pool.
  1107. *
  1108. * @see #setTestWhileIdle
  1109. * @see #getTestWhileIdle
  1110. * @see #getTimeBetweenEvictionRunsMillis
  1111. * @see #setTimeBetweenEvictionRunsMillis
  1112. */
  1113. private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE;
  1114. /**
  1115. * The number of milliseconds to sleep between runs of the
  1116. * idle object evictor thread.
  1117. * When non-positive, no idle object evictor thread will be
  1118. * run.
  1119. *
  1120. * @see #setTimeBetweenEvictionRunsMillis
  1121. * @see #getTimeBetweenEvictionRunsMillis
  1122. */
  1123. private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
  1124. /**
  1125. * The number of objects to examine during each run of the
  1126. * idle object evictor thread (if any).
  1127. * <p>
  1128. * When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
  1129. * tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
  1130. * idle objects will be tested per run.
  1131. *
  1132. * @see #setNumTestsPerEvictionRun
  1133. * @see #getNumTestsPerEvictionRun
  1134. * @see #getTimeBetweenEvictionRunsMillis
  1135. * @see #setTimeBetweenEvictionRunsMillis
  1136. */
  1137. private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
  1138. /**
  1139. * The minimum amount of time an object may sit idle in the pool
  1140. * before it is eligable for eviction by the idle object evictor
  1141. * (if any).
  1142. * When non-positive, no objects will be evicted from the pool
  1143. * due to idle time alone.
  1144. *
  1145. * @see #setMinEvictableIdleTimeMillis
  1146. * @see #getMinEvictableIdleTimeMillis
  1147. * @see #getTimeBetweenEvictionRunsMillis
  1148. * @see #setTimeBetweenEvictionRunsMillis
  1149. */
  1150. private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
  1151. /** My pool. */
  1152. private CursorableLinkedList _pool = null;
  1153. /** My {@link PoolableObjectFactory}. */
  1154. private PoolableObjectFactory _factory = null;
  1155. /**
  1156. * The number of objects {@link #borrowObject} borrowed
  1157. * from the pool, but not yet returned.
  1158. */
  1159. private int _numActive = 0;
  1160. /**
  1161. * My idle object eviction thread, if any.
  1162. */
  1163. private Evictor _evictor = null;
  1164. private CursorableLinkedList.Cursor _evictionCursor = null;
  1165. }