You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2021/02/15 22:15:38 UTC
[commons-pool] 06/06: Sort members.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-pool.git
commit db7c2ae33204b0535b041bdaff44be622001aefd
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Mon Feb 15 17:15:27 2021 -0500
Sort members.
---
.../commons/pool2/impl/BaseGenericObjectPool.java | 2048 ++++++++++----------
.../commons/pool2/impl/BaseObjectPoolConfig.java | 680 +++----
.../org/apache/commons/pool2/impl/CallStack.java | 18 +-
.../commons/pool2/impl/DefaultPooledObject.java | 252 +--
.../pool2/impl/DefaultPooledObjectInfo.java | 14 +-
.../pool2/impl/DefaultPooledObjectInfoMBean.java | 28 +-
.../apache/commons/pool2/impl/EvictionTimer.java | 198 +-
.../commons/pool2/impl/GenericKeyedObjectPool.java | 1822 ++++++++---------
.../pool2/impl/GenericKeyedObjectPoolConfig.java | 100 +-
.../pool2/impl/GenericKeyedObjectPoolMXBean.java | 180 +-
.../commons/pool2/impl/GenericObjectPool.java | 1398 ++++++-------
.../pool2/impl/GenericObjectPoolConfig.java | 72 +-
.../pool2/impl/GenericObjectPoolMXBean.java | 206 +-
.../apache/commons/pool2/impl/NoOpCallStack.java | 8 +-
.../commons/pool2/impl/PooledSoftReference.java | 34 +-
.../pool2/impl/SecurityManagerCallStack.java | 92 +-
.../pool2/impl/SoftReferenceObjectPool.java | 374 ++--
.../commons/pool2/impl/ThrowableCallStack.java | 36 +-
18 files changed, 3780 insertions(+), 3780 deletions(-)
diff --git a/src/main/java/org/apache/commons/pool2/impl/BaseGenericObjectPool.java b/src/main/java/org/apache/commons/pool2/impl/BaseGenericObjectPool.java
index 78e5457..04c56e9 100644
--- a/src/main/java/org/apache/commons/pool2/impl/BaseGenericObjectPool.java
+++ b/src/main/java/org/apache/commons/pool2/impl/BaseGenericObjectPool.java
@@ -56,15 +56,259 @@ import org.apache.commons.pool2.SwallowedExceptionListener;
*/
public abstract class BaseGenericObjectPool<T> extends BaseObject {
+ /**
+ * The idle object eviction iterator. Holds a reference to the idle objects.
+ */
+ class EvictionIterator implements Iterator<PooledObject<T>> {
+
+ private final Deque<PooledObject<T>> idleObjects;
+ private final Iterator<PooledObject<T>> idleObjectIterator;
+
+ /**
+ * Create an EvictionIterator for the provided idle instance deque.
+ * @param idleObjects underlying deque
+ */
+ EvictionIterator(final Deque<PooledObject<T>> idleObjects) {
+ this.idleObjects = idleObjects;
+
+ if (getLifo()) {
+ idleObjectIterator = idleObjects.descendingIterator();
+ } else {
+ idleObjectIterator = idleObjects.iterator();
+ }
+ }
+
+ /**
+ * Gets the idle object deque referenced by this iterator.
+ * @return the idle object deque
+ */
+ public Deque<PooledObject<T>> getIdleObjects() {
+ return idleObjects;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean hasNext() {
+ return idleObjectIterator.hasNext();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public PooledObject<T> next() {
+ return idleObjectIterator.next();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public void remove() {
+ idleObjectIterator.remove();
+ }
+
+ }
+
+ /**
+ * The idle object evictor {@link TimerTask}.
+ *
+ * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis
+ */
+ class Evictor implements Runnable {
+
+ private ScheduledFuture<?> scheduledFuture;
+
+ /**
+ * Cancels the scheduled future.
+ */
+ void cancel() {
+ scheduledFuture.cancel(false);
+ }
+
+
+ /**
+ * Run pool maintenance. Evict objects qualifying for eviction and then
+ * ensure that the minimum number of idle instances are available.
+ * Since the Timer that invokes Evictors is shared for all Pools but
+ * pools may exist in different class loaders, the Evictor ensures that
+ * any actions taken are under the class loader of the factory
+ * associated with the pool.
+ */
+ @Override
+ public void run() {
+ final ClassLoader savedClassLoader =
+ Thread.currentThread().getContextClassLoader();
+ try {
+ if (factoryClassLoader != null) {
+ // Set the class loader for the factory
+ final ClassLoader cl = factoryClassLoader.get();
+ if (cl == null) {
+ // The pool has been dereferenced and the class loader
+ // GC'd. Cancel this timer so the pool can be GC'd as
+ // well.
+ cancel();
+ return;
+ }
+ Thread.currentThread().setContextClassLoader(cl);
+ }
+
+ // Evict from the pool
+ try {
+ evict();
+ } catch(final Exception e) {
+ swallowException(e);
+ } catch(final OutOfMemoryError oome) {
+ // Log problem but give evictor thread a chance to continue
+ // in case error is recoverable
+ oome.printStackTrace(System.err);
+ }
+ // Re-create idle instances.
+ try {
+ ensureMinIdle();
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ } finally {
+ // Restore the previous CCL
+ Thread.currentThread().setContextClassLoader(savedClassLoader);
+ }
+ }
+
+
+ /**
+ * Sets the scheduled future.
+ *
+ * @param scheduledFuture the scheduled future.
+ */
+ void setScheduledFuture(final ScheduledFuture<?> scheduledFuture) {
+ this.scheduledFuture = scheduledFuture;
+ }
+
+ }
+
+ /**
+ * Wrapper for objects under management by the pool.
+ *
+ * GenericObjectPool and GenericKeyedObjectPool maintain references to all
+ * objects under management using maps keyed on the objects. This wrapper
+ * class ensures that objects can work as hash keys.
+ *
+ * @param <T> type of objects in the pool
+ */
+ static class IdentityWrapper<T> {
+ /** Wrapped object */
+ private final T instance;
+
+ /**
+ * Create a wrapper for an instance.
+ *
+ * @param instance object to wrap
+ */
+ public IdentityWrapper(final T instance) {
+ this.instance = instance;
+ }
+
+ @Override
+ @SuppressWarnings("rawtypes")
+ public boolean equals(final Object other) {
+ return other instanceof IdentityWrapper &&
+ ((IdentityWrapper) other).instance == instance;
+ }
+
+ /**
+ * @return the wrapped object
+ */
+ public T getObject() {
+ return instance;
+ }
+
+ @Override
+ public int hashCode() {
+ return System.identityHashCode(instance);
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("IdentityWrapper [instance=");
+ builder.append(instance);
+ builder.append("]");
+ return builder.toString();
+ }
+ }
+ /**
+ * Maintains a cache of values for a single metric and reports
+ * statistics on the cached values.
+ */
+ private class StatsStore {
+
+ private final AtomicLong values[];
+ private final int size;
+ private int index;
+
+ /**
+ * Create a StatsStore with the given cache size.
+ *
+ * @param size number of values to maintain in the cache.
+ */
+ public StatsStore(final int size) {
+ this.size = size;
+ values = new AtomicLong[size];
+ for (int i = 0; i < size; i++) {
+ values[i] = new AtomicLong(-1);
+ }
+ }
+
+ /**
+ * Adds a value to the cache. If the cache is full, one of the
+ * existing values is replaced by the new value.
+ *
+ * @param value new value to add to the cache.
+ */
+ public synchronized void add(final long value) {
+ values[index].set(value);
+ index++;
+ if (index == size) {
+ index = 0;
+ }
+ }
+
+ /**
+ * Gets the mean of the cached values.
+ *
+ * @return the mean of the cache, truncated to long
+ */
+ public long getMean() {
+ double result = 0;
+ int counter = 0;
+ for (int i = 0; i < size; i++) {
+ final long value = values[i].get();
+ if (value != -1) {
+ counter++;
+ result = result * ((counter - 1) / (double) counter) +
+ value/(double) counter;
+ }
+ }
+ return (long) result;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("StatsStore [values=");
+ builder.append(Arrays.toString(values));
+ builder.append(", size=");
+ builder.append(size);
+ builder.append(", index=");
+ builder.append(index);
+ builder.append("]");
+ return builder.toString();
+ }
+ }
// Constants
/**
* The size of the caches used to store historical data for some attributes
* so that rolling means may be calculated.
*/
public static final int MEAN_TIMING_STATS_CACHE_SIZE = 100;
-
private static final String EVICTION_POLICY_TYPE_NAME = EvictionPolicy.class.getName();
-
// Configuration attributes
private volatile int maxTotal = GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL;
private volatile boolean blockWhenExhausted = BaseObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED;
@@ -77,14 +321,16 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
private volatile boolean testWhileIdle = BaseObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE;
private volatile Duration timeBetweenEvictionRuns = BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS;
private volatile int numTestsPerEvictionRun = BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
+
private volatile Duration minEvictableIdleTime = BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME;
private volatile Duration softMinEvictableIdleTime = BaseObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME;
private volatile EvictionPolicy<T> evictionPolicy;
private volatile Duration evictorShutdownTimeout = BaseObjectPoolConfig.DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT;
-
// Internal (primarily state) attributes
final Object closeLock = new Object();
volatile boolean closed = false;
+
+
final Object evictionLock = new Object();
private Evictor evictor = null; // @GuardedBy("evictionLock")
EvictionIterator evictionIterator = null; // @GuardedBy("evictionLock")
@@ -95,8 +341,6 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
* avoid potential memory leaks if the Pool is discarded rather than closed.
*/
private final WeakReference<ClassLoader> factoryClassLoader;
-
-
// Monitoring (primarily JMX) attributes
private final ObjectName objectName;
private final String creationStackTrace;
@@ -107,11 +351,16 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
final AtomicLong destroyedByEvictorCount = new AtomicLong(0);
final AtomicLong destroyedByBorrowValidationCount = new AtomicLong(0);
private final StatsStore activeTimes = new StatsStore(MEAN_TIMING_STATS_CACHE_SIZE);
+
+
private final StatsStore idleTimes = new StatsStore(MEAN_TIMING_STATS_CACHE_SIZE);
+
+
private final StatsStore waitTimes = new StatsStore(MEAN_TIMING_STATS_CACHE_SIZE);
+
private final AtomicLong maxBorrowWaitTimeMillis = new AtomicLong(0L);
- private volatile SwallowedExceptionListener swallowedExceptionListener = null;
+ private volatile SwallowedExceptionListener swallowedExceptionListener = null;
/**
* Handles JMX registration (if required) and the initialization required for
@@ -144,36 +393,40 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
fairness = config.getFairness();
}
-
/**
- * Gets the maximum number of objects that can be allocated by the pool
- * (checked out to clients, or idle awaiting checkout) at a given time. When
- * negative, there is no limit to the number of objects that can be
- * managed by the pool at one time.
- *
- * @return the cap on the total number of object instances managed by the
- * pool.
- *
- * @see #setMaxTotal
+ * Verifies that the pool is open.
+ * @throws IllegalStateException if the pool is closed.
*/
- public final int getMaxTotal() {
- return maxTotal;
+ final void assertOpen() throws IllegalStateException {
+ if (isClosed()) {
+ throw new IllegalStateException("Pool not open");
+ }
}
/**
- * Sets the cap on the number of objects that can be allocated by the pool
- * (checked out to clients, or idle awaiting checkout) at a given time. Use
- * a negative value for no limit.
- *
- * @param maxTotal The cap on the total number of object instances managed
- * by the pool. Negative values mean that there is no limit
- * to the number of objects allocated by the pool.
+ * Closes the pool, destroys the remaining idle objects and, if registered
+ * in JMX, deregisters it.
+ */
+ public abstract void close();
+
+ /**
+ * Tries to ensure that the configured minimum number of idle instances are
+ * available in the pool.
+ * @throws Exception if an error occurs creating idle instances
+ */
+ abstract void ensureMinIdle() throws Exception;
+
+ /**
+ * <p>Perform {@code numTests} idle object eviction tests, evicting
+ * examined objects that meet the criteria for eviction. If
+ * {@code testWhileIdle} is true, examined objects are validated
+ * when visited (and removed if invalid); otherwise only objects that
+ * have been idle for more than {@code minEvicableIdleTimeMillis}
+ * are removed.</p>
*
- * @see #getMaxTotal
+ * @throws Exception when there is a problem evicting idle objects.
*/
- public final void setMaxTotal(final int maxTotal) {
- this.maxTotal = maxTotal;
- }
+ public abstract void evict() throws Exception;
/**
* Gets whether to block when the {@code borrowObject()} method is
@@ -190,97 +443,111 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Sets whether to block when the {@code borrowObject()} method is
- * invoked when the pool is exhausted (the maximum number of "active"
- * objects has been reached).
- *
- * @param blockWhenExhausted {@code true} if
- * {@code borrowObject()} should block
- * when the pool is exhausted
- *
- * @see #getBlockWhenExhausted
+ * The total number of objects successfully borrowed from this pool over the
+ * lifetime of the pool.
+ * @return the borrowed object count
*/
- public final void setBlockWhenExhausted(final boolean blockWhenExhausted) {
- this.blockWhenExhausted = blockWhenExhausted;
+ public final long getBorrowedCount() {
+ return borrowedCount.get();
}
/**
- * Initializes the receiver with the given configuration.
- *
- * @param config Initialization source.
+ * The total number of objects created for this pool over the lifetime of
+ * the pool.
+ * @return the created object count
*/
- protected void setConfig(final BaseObjectPoolConfig<T> config) {
- setLifo(config.getLifo());
- setMaxWaitMillis(config.getMaxWaitMillis());
- setBlockWhenExhausted(config.getBlockWhenExhausted());
- setTestOnCreate(config.getTestOnCreate());
- setTestOnBorrow(config.getTestOnBorrow());
- setTestOnReturn(config.getTestOnReturn());
- setTestWhileIdle(config.getTestWhileIdle());
- setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun());
- setMinEvictableIdleTime(config.getMinEvictableIdleTime());
- setTimeBetweenEvictionRuns(config.getTimeBetweenEvictionRuns());
- setSoftMinEvictableIdleTime(config.getSoftMinEvictableIdleTime());
- final EvictionPolicy<T> policy = config.getEvictionPolicy();
- if (policy == null) {
- // Use the class name (pre-2.6.0 compatible)
- setEvictionPolicyClassName(config.getEvictionPolicyClassName());
- } else {
- // Otherwise, use the class (2.6.0 feature)
- setEvictionPolicy(policy);
- }
- setEvictorShutdownTimeout(config.getEvictorShutdownTimeout());
+ public final long getCreatedCount() {
+ return createdCount.get();
}
/**
- * Gets the maximum amount of time (in milliseconds) the
- * {@code borrowObject()} method should block before throwing an
- * exception when the pool is exhausted and
- * {@link #getBlockWhenExhausted} is true. When less than 0, the
- * {@code borrowObject()} method may block indefinitely.
- *
- * @return the maximum number of milliseconds {@code borrowObject()}
- * will block.
+ * Provides the stack trace for the call that created this pool. JMX
+ * registration may trigger a memory leak so it is important that pools are
+ * deregistered when no longer used by calling the {@link #close()} method.
+ * This method is provided to assist with identifying code that creates but
+ * does not close it thereby creating a memory leak.
+ * @return pool creation stack trace
+ */
+ public final String getCreationStackTrace() {
+ return creationStackTrace;
+ }
+
+ /**
+ * The total number of objects destroyed by this pool as a result of failing
+ * validation during {@code borrowObject()} over the lifetime of the
+ * pool.
+ * @return validation destroyed object count
+ */
+ public final long getDestroyedByBorrowValidationCount() {
+ return destroyedByBorrowValidationCount.get();
+ }
+
+ /**
+ * The total number of objects destroyed by the evictor associated with this
+ * pool over the lifetime of the pool.
+ * @return the evictor destroyed object count
+ */
+ public final long getDestroyedByEvictorCount() {
+ return destroyedByEvictorCount.get();
+ }
+
+ /**
+ * The total number of objects destroyed by this pool over the lifetime of
+ * the pool.
+ * @return the destroyed object count
+ */
+ public final long getDestroyedCount() {
+ return destroyedCount.get();
+ }
+
+ /**
+ * Gets the {@link EvictionPolicy} defined for this pool.
*
- * @see #setMaxWaitMillis
- * @see #setBlockWhenExhausted
+ * @return the eviction policy
+ * @since 2.4
+ * @since 2.6.0 Changed access from protected to public.
*/
- public final long getMaxWaitMillis() {
- return maxWait.toMillis();
+ public EvictionPolicy<T> getEvictionPolicy() {
+ return evictionPolicy;
}
/**
- * Sets the maximum amount of time (in milliseconds) the
- * {@code borrowObject()} method should block before throwing an
- * exception when the pool is exhausted and
- * {@link #getBlockWhenExhausted} is true. When less than 0, the
- * {@code borrowObject()} method may block indefinitely.
+ * Gets the name of the {@link EvictionPolicy} implementation that is
+ * used by this pool.
*
- * @param maxWaitMillis the maximum number of milliseconds
- * {@code borrowObject()} will block or negative
- * for indefinitely.
+ * @return The fully qualified class name of the {@link EvictionPolicy}
*
- * @see #getMaxWaitMillis
- * @see #setBlockWhenExhausted
+ * @see #setEvictionPolicyClassName(String)
*/
- public final void setMaxWaitMillis(final long maxWaitMillis) {
- this.maxWait = Duration.ofMillis(maxWaitMillis);
+ public final String getEvictionPolicyClassName() {
+ return evictionPolicy.getClass().getName();
}
/**
- * Gets whether the pool has LIFO (last in, first out) behavior with
- * respect to idle objects - always returning the most recently used object
- * from the pool, or as a FIFO (first in, first out) queue, where the pool
- * always returns the oldest object in the idle object pool.
+ * Gets the timeout that will be used when waiting for the Evictor to
+ * shutdown if this pool is closed and it is the only pool still using the
+ * the value for the Evictor.
*
- * @return {@code true} if the pool is configured with LIFO behavior
- * or {@code false} if the pool is configured with FIFO
- * behavior
+ * @return The timeout that will be used while waiting for
+ * the Evictor to shut down.
+ * @since 2.10.0
+ */
+ public final Duration getEvictorShutdownTimeout() {
+ return evictorShutdownTimeout;
+ }
+
+ /**
+ * Gets the timeout that will be used when waiting for the Evictor to
+ * shutdown if this pool is closed and it is the only pool still using the
+ * the value for the Evictor.
*
- * @see #setLifo
+ * @return The timeout in milliseconds that will be used while waiting for
+ * the Evictor to shut down.
+ * @deprecated Use {@link #getEvictorShutdownTimeout()}.
*/
- public final boolean getLifo() {
- return lifo;
+ @Deprecated
+ public final long getEvictorShutdownTimeoutMillis() {
+ return evictorShutdownTimeout.toMillis();
}
/**
@@ -295,56 +562,235 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Sets whether the pool has LIFO (last in, first out) behavior with
+ * Provides the name under which the pool has been registered with the
+ * platform MBean server or {@code null} if the pool has not been
+ * registered.
+ * @return the JMX name
+ */
+ public final ObjectName getJmxName() {
+ return objectName;
+ }
+
+ /**
+ * Gets whether the pool has LIFO (last in, first out) behavior with
* respect to idle objects - always returning the most recently used object
* from the pool, or as a FIFO (first in, first out) queue, where the pool
* always returns the oldest object in the idle object pool.
*
- * @param lifo {@code true} if the pool is to be configured with LIFO
- * behavior or {@code false} if the pool is to be
- * configured with FIFO behavior
+ * @return {@code true} if the pool is configured with LIFO behavior
+ * or {@code false} if the pool is configured with FIFO
+ * behavior
*
- * @see #getLifo()
+ * @see #setLifo
*/
- public final void setLifo(final boolean lifo) {
- this.lifo = lifo;
+ public final boolean getLifo() {
+ return lifo;
}
/**
- * Gets whether objects created for the pool will be validated before
- * being returned from the {@code borrowObject()} method. Validation is
- * performed by the {@code validateObject()} method of the factory
- * associated with the pool. If the object fails to validate, then
- * {@code borrowObject()} will fail.
- *
- * @return {@code true} if newly created objects are validated before
- * being returned from the {@code borrowObject()} method
- *
- * @see #setTestOnCreate
- *
- * @since 2.2
+ * The maximum time a thread has waited to borrow objects from the pool.
+ * @return maximum wait time in milliseconds since the pool was created
*/
- public final boolean getTestOnCreate() {
- return testOnCreate;
+ public final long getMaxBorrowWaitTimeMillis() {
+ return maxBorrowWaitTimeMillis.get();
}
/**
- * Sets whether objects created for the pool will be validated before
- * being returned from the {@code borrowObject()} method. Validation is
- * performed by the {@code validateObject()} method of the factory
- * associated with the pool. If the object fails to validate, then
- * {@code borrowObject()} will fail.
- *
- * @param testOnCreate {@code true} if newly created objects should be
- * validated before being returned from the
- * {@code borrowObject()} method
+ * Gets the maximum number of objects that can be allocated by the pool
+ * (checked out to clients, or idle awaiting checkout) at a given time. When
+ * negative, there is no limit to the number of objects that can be
+ * managed by the pool at one time.
*
- * @see #getTestOnCreate
+ * @return the cap on the total number of object instances managed by the
+ * pool.
*
- * @since 2.2
+ * @see #setMaxTotal
*/
- public final void setTestOnCreate(final boolean testOnCreate) {
- this.testOnCreate = testOnCreate;
+ public final int getMaxTotal() {
+ return maxTotal;
+ }
+
+ /**
+ * Gets the maximum amount of time (in milliseconds) the
+ * {@code borrowObject()} method should block before throwing an
+ * exception when the pool is exhausted and
+ * {@link #getBlockWhenExhausted} is true. When less than 0, the
+ * {@code borrowObject()} method may block indefinitely.
+ *
+ * @return the maximum number of milliseconds {@code borrowObject()}
+ * will block.
+ *
+ * @see #setMaxWaitMillis
+ * @see #setBlockWhenExhausted
+ */
+ public final long getMaxWaitMillis() {
+ return maxWait.toMillis();
+ }
+
+ /**
+ * The mean time objects are active for based on the last {@link
+ * #MEAN_TIMING_STATS_CACHE_SIZE} objects returned to the pool.
+ * @return mean time an object has been checked out from the pool among
+ * recently returned objects
+ */
+ public final long getMeanActiveTimeMillis() {
+ return activeTimes.getMean();
+ }
+
+ /**
+ * The mean time threads wait to borrow an object based on the last {@link
+ * #MEAN_TIMING_STATS_CACHE_SIZE} objects borrowed from the pool.
+ * @return mean time in milliseconds that a recently served thread has had
+ * to wait to borrow an object from the pool
+ */
+ public final long getMeanBorrowWaitTimeMillis() {
+ return waitTimes.getMean();
+ }
+
+ /**
+ * The mean time objects are idle for based on the last {@link
+ * #MEAN_TIMING_STATS_CACHE_SIZE} objects borrowed from the pool.
+ * @return mean time an object has been idle in the pool among recently
+ * borrowed objects
+ */
+ public final long getMeanIdleTimeMillis() {
+ return idleTimes.getMean();
+ }
+
+ /**
+ * Gets the minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction by the idle object evictor (if any -
+ * see {@link #setTimeBetweenEvictionRuns(Duration)}). When non-positive,
+ * no objects will be evicted from the pool due to idle time alone.
+ *
+ * @return minimum amount of time an object may sit idle in the pool before
+ * it is eligible for eviction
+ *
+ * @see #setMinEvictableIdleTimeMillis
+ * @see #setTimeBetweenEvictionRunsMillis
+ * @since 2.10.0
+ */
+ public final Duration getMinEvictableIdleTime() {
+ return minEvictableIdleTime;
+ }
+
+ /**
+ * Gets the minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction by the idle object evictor (if any -
+ * see {@link #setTimeBetweenEvictionRunsMillis(long)}). When non-positive,
+ * no objects will be evicted from the pool due to idle time alone.
+ *
+ * @return minimum amount of time an object may sit idle in the pool before
+ * it is eligible for eviction
+ *
+ * @see #setMinEvictableIdleTimeMillis
+ * @see #setTimeBetweenEvictionRunsMillis
+ * @deprecated Use {@link #getMinEvictableIdleTime()}.
+ */
+ @Deprecated
+ public final long getMinEvictableIdleTimeMillis() {
+ return minEvictableIdleTime.toMillis();
+ }
+
+ /**
+ * The number of instances currently idle in this pool.
+ * @return count of instances available for checkout from the pool
+ */
+ public abstract int getNumIdle();
+
+ /**
+ * Gets the maximum number of objects to examine during each run (if any)
+ * of the idle object evictor thread. When positive, the number of tests
+ * performed for a run will be the minimum of the configured value and the
+ * number of idle instances in the pool. When negative, the number of tests
+ * performed will be <code>ceil({@link #getNumIdle}/
+ * abs({@link #getNumTestsPerEvictionRun}))</code> which means that when the
+ * value is {@code -n} roughly one nth of the idle objects will be
+ * tested per run.
+ *
+ * @return max number of objects to examine during each evictor run
+ *
+ * @see #setNumTestsPerEvictionRun
+ * @see #setTimeBetweenEvictionRunsMillis
+ */
+ public final int getNumTestsPerEvictionRun() {
+ return numTestsPerEvictionRun;
+ }
+
+ /**
+ * The total number of objects returned to this pool over the lifetime of
+ * the pool. This excludes attempts to return the same object multiple
+ * times.
+ * @return the returned object count
+ */
+ public final long getReturnedCount() {
+ return returnedCount.get();
+ }
+
+ /**
+ * Gets the minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction by the idle object evictor (if any -
+ * see {@link #setTimeBetweenEvictionRuns(Duration)}),
+ * with the extra condition that at least {@code minIdle} object
+ * instances remain in the pool. This setting is overridden by
+ * {@link #getMinEvictableIdleTime} (that is, if
+ * {@link #getMinEvictableIdleTime} is positive, then
+ * {@link #getSoftMinEvictableIdleTime} is ignored).
+ *
+ * @return minimum amount of time an object may sit idle in the pool before
+ * it is eligible for eviction if minIdle instances are available
+ *
+ * @see #setSoftMinEvictableIdleTime(Duration)
+ * @since 2.10.0
+ */
+ public final Duration getSoftMinEvictableIdleTime() {
+ return softMinEvictableIdleTime;
+ }
+
+ /**
+ * Gets the minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction by the idle object evictor (if any -
+ * see {@link #setTimeBetweenEvictionRunsMillis(long)}),
+ * with the extra condition that at least {@code minIdle} object
+ * instances remain in the pool. This setting is overridden by
+ * {@link #getMinEvictableIdleTimeMillis} (that is, if
+ * {@link #getMinEvictableIdleTimeMillis} is positive, then
+ * {@link #getSoftMinEvictableIdleTimeMillis} is ignored).
+ *
+ * @return minimum amount of time an object may sit idle in the pool before
+ * it is eligible for eviction if minIdle instances are available
+ *
+ * @see #setSoftMinEvictableIdleTimeMillis
+ * @deprecated Use {@link #getSoftMinEvictableIdleTime()}.
+ */
+ @Deprecated
+ public final long getSoftMinEvictableIdleTimeMillis() {
+ return softMinEvictableIdleTime.toMillis();
+ }
+
+ /**
+ * Gets the stack trace of an exception as a string.
+ * @param e exception to trace
+ * @return exception stack trace as a string
+ */
+ private String getStackTrace(final Exception e) {
+ // Need the exception in string form to prevent the retention of
+ // references to classes in the stack trace that could trigger a memory
+ // leak in a container environment.
+ final Writer w = new StringWriter();
+ final PrintWriter pw = new PrintWriter(w);
+ e.printStackTrace(pw);
+ return w.toString();
+ }
+
+ /**
+ * The listener used (if any) to receive notifications of exceptions
+ * unavoidably swallowed by the pool.
+ *
+ * @return The listener or {@code null} for no listener
+ */
+ public final SwallowedExceptionListener getSwallowedExceptionListener() {
+ return swallowedExceptionListener;
}
/**
@@ -365,21 +811,21 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Sets whether objects borrowed from the pool will be validated before
+ * Gets whether objects created for the pool will be validated before
* being returned from the {@code borrowObject()} method. Validation is
* performed by the {@code validateObject()} method of the factory
- * associated with the pool. If the object fails to validate, it will be
- * removed from the pool and destroyed, and a new attempt will be made to
- * borrow an object from the pool.
+ * associated with the pool. If the object fails to validate, then
+ * {@code borrowObject()} will fail.
*
- * @param testOnBorrow {@code true} if objects should be validated
- * before being returned from the
- * {@code borrowObject()} method
+ * @return {@code true} if newly created objects are validated before
+ * being returned from the {@code borrowObject()} method
*
- * @see #getTestOnBorrow
+ * @see #setTestOnCreate
+ *
+ * @since 2.2
*/
- public final void setTestOnBorrow(final boolean testOnBorrow) {
- this.testOnBorrow = testOnBorrow;
+ public final boolean getTestOnCreate() {
+ return testOnCreate;
}
/**
@@ -399,23 +845,6 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Sets whether objects borrowed from the pool will be validated when
- * they are returned to the pool via the {@code returnObject()} method.
- * Validation is performed by the {@code validateObject()} method of
- * the factory associated with the pool. Returning objects that fail validation
- * are destroyed rather then being returned the pool.
- *
- * @param testOnReturn {@code true} if objects are validated on
- * return to the pool via the
- * {@code returnObject()} method
- *
- * @see #getTestOnReturn
- */
- public final void setTestOnReturn(final boolean testOnReturn) {
- this.testOnReturn = testOnReturn;
- }
-
- /**
* Gets whether objects sitting idle in the pool will be validated by the
* idle object evictor (if any - see
* {@link #setTimeBetweenEvictionRuns(Duration)}). Validation is performed
@@ -433,26 +862,6 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Sets whether objects sitting idle in the pool will be validated by the
- * idle object evictor (if any - see
- * {@link #setTimeBetweenEvictionRuns(Duration)}). Validation is performed
- * by the {@code validateObject()} method of the factory associated
- * with the pool. If the object fails to validate, it will be removed from
- * the pool and destroyed. Note that setting this property has no effect
- * unless the idle object evictor is enabled by setting
- * {@code timeBetweenEvictionRunsMillis} to a positive value.
- *
- * @param testWhileIdle
- * {@code true} so objects will be validated by the evictor
- *
- * @see #getTestWhileIdle
- * @see #setTimeBetweenEvictionRuns
- */
- public final void setTestWhileIdle(final boolean testWhileIdle) {
- this.testWhileIdle = testWhileIdle;
- }
-
- /**
* Gets the duration to sleep between runs of the idle
* object evictor thread. When non-positive, no idle object evictor thread
* will be run.
@@ -482,260 +891,184 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Sets the number of milliseconds to sleep between runs of the idle object evictor thread.
- * <ul>
- * <li>When positive, the idle object evictor thread starts.</li>
- * <li>When non-positive, no idle object evictor thread runs.</li>
- * </ul>
- *
- * @param timeBetweenEvictionRuns
- * duration to sleep between evictor runs
- *
- * @see #getTimeBetweenEvictionRunsMillis
- * @since 2.10.0
+ * Has this pool instance been closed.
+ * @return {@code true} when this pool has been closed.
*/
- public final void setTimeBetweenEvictionRuns(final Duration timeBetweenEvictionRuns) {
- this.timeBetweenEvictionRuns = timeBetweenEvictionRuns;
- startEvictor(this.timeBetweenEvictionRuns);
+ public final boolean isClosed() {
+ return closed;
}
/**
- * Sets the number of milliseconds to sleep between runs of the idle object evictor thread.
- * <ul>
- * <li>When positive, the idle object evictor thread starts.</li>
- * <li>When non-positive, no idle object evictor thread runs.</li>
- * </ul>
- *
- * @param timeBetweenEvictionRunsMillis
- * number of milliseconds to sleep between evictor runs
+ * Registers the pool with the platform MBean server.
+ * The registered name will be
+ * {@code jmxNameBase + jmxNamePrefix + i} where i is the least
+ * integer greater than or equal to 1 such that the name is not already
+ * registered. Swallows MBeanRegistrationException, NotCompliantMBeanException
+ * returning null.
*
- * @see #getTimeBetweenEvictionRunsMillis
- * @deprecated Use {@link #setTimeBetweenEvictionRuns(Duration)}.
+ * @param config Pool configuration
+ * @param jmxNameBase default base JMX name for this pool
+ * @param jmxNamePrefix name prefix
+ * @return registered ObjectName, null if registration fails
*/
- @Deprecated
- public final void setTimeBetweenEvictionRunsMillis(final long timeBetweenEvictionRunsMillis) {
- this.timeBetweenEvictionRuns = Duration.ofMillis(timeBetweenEvictionRunsMillis);
- startEvictor(timeBetweenEvictionRuns);
+ private ObjectName jmxRegister(final BaseObjectPoolConfig<T> config,
+ final String jmxNameBase, String jmxNamePrefix) {
+ ObjectName newObjectName = null;
+ final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+ int i = 1;
+ boolean registered = false;
+ String base = config.getJmxNameBase();
+ if (base == null) {
+ base = jmxNameBase;
+ }
+ while (!registered) {
+ try {
+ ObjectName objName;
+ // Skip the numeric suffix for the first pool in case there is
+ // only one so the names are cleaner.
+ if (i == 1) {
+ objName = new ObjectName(base + jmxNamePrefix);
+ } else {
+ objName = new ObjectName(base + jmxNamePrefix + i);
+ }
+ mbs.registerMBean(this, objName);
+ newObjectName = objName;
+ registered = true;
+ } catch (final MalformedObjectNameException e) {
+ if (BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX.equals(
+ jmxNamePrefix) && jmxNameBase.equals(base)) {
+ // Shouldn't happen. Skip registration if it does.
+ registered = true;
+ } else {
+ // Must be an invalid name. Use the defaults instead.
+ jmxNamePrefix =
+ BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX;
+ base = jmxNameBase;
+ }
+ } catch (final InstanceAlreadyExistsException e) {
+ // Increment the index and try again
+ i++;
+ } catch (final MBeanRegistrationException | NotCompliantMBeanException e) {
+ // Shouldn't happen. Skip registration if it does.
+ registered = true;
+ }
+ }
+ return newObjectName;
}
/**
- * Gets the maximum number of objects to examine during each run (if any)
- * of the idle object evictor thread. When positive, the number of tests
- * performed for a run will be the minimum of the configured value and the
- * number of idle instances in the pool. When negative, the number of tests
- * performed will be <code>ceil({@link #getNumIdle}/
- * abs({@link #getNumTestsPerEvictionRun}))</code> which means that when the
- * value is {@code -n} roughly one nth of the idle objects will be
- * tested per run.
- *
- * @return max number of objects to examine during each evictor run
- *
- * @see #setNumTestsPerEvictionRun
- * @see #setTimeBetweenEvictionRunsMillis
+ * Unregisters this pool's MBean.
*/
- public final int getNumTestsPerEvictionRun() {
- return numTestsPerEvictionRun;
+ final void jmxUnregister() {
+ if (objectName != null) {
+ try {
+ ManagementFactory.getPlatformMBeanServer().unregisterMBean(
+ objectName);
+ } catch (final MBeanRegistrationException | InstanceNotFoundException e) {
+ swallowException(e);
+ }
+ }
}
/**
- * Sets the maximum number of objects to examine during each run (if any)
- * of the idle object evictor thread. When positive, the number of tests
- * performed for a run will be the minimum of the configured value and the
- * number of idle instances in the pool. When negative, the number of tests
- * performed will be <code>ceil({@link #getNumIdle}/
- * abs({@link #getNumTestsPerEvictionRun}))</code> which means that when the
- * value is {@code -n} roughly one nth of the idle objects will be
- * tested per run.
- *
- * @param numTestsPerEvictionRun
- * max number of objects to examine during each evictor run
- *
- * @see #getNumTestsPerEvictionRun
- * @see #setTimeBetweenEvictionRunsMillis
+ * Marks the object as returning to the pool.
+ * @param pooledObject instance to return to the keyed pool
*/
- public final void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) {
- this.numTestsPerEvictionRun = numTestsPerEvictionRun;
+ protected void markReturningState(final PooledObject<T> pooledObject) {
+ synchronized(pooledObject) {
+ final PooledObjectState state = pooledObject.getState();
+ if (state != PooledObjectState.ALLOCATED) {
+ throw new IllegalStateException(
+ "Object has already been returned to this pool or is invalid");
+ }
+ pooledObject.markReturning(); // Keep from being marked abandoned
+ }
}
/**
- * Gets the minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction by the idle object evictor (if any -
- * see {@link #setTimeBetweenEvictionRuns(Duration)}). When non-positive,
- * no objects will be evicted from the pool due to idle time alone.
+ * Sets whether to block when the {@code borrowObject()} method is
+ * invoked when the pool is exhausted (the maximum number of "active"
+ * objects has been reached).
*
- * @return minimum amount of time an object may sit idle in the pool before
- * it is eligible for eviction
+ * @param blockWhenExhausted {@code true} if
+ * {@code borrowObject()} should block
+ * when the pool is exhausted
*
- * @see #setMinEvictableIdleTimeMillis
- * @see #setTimeBetweenEvictionRunsMillis
- * @since 2.10.0
+ * @see #getBlockWhenExhausted
*/
- public final Duration getMinEvictableIdleTime() {
- return minEvictableIdleTime;
+ public final void setBlockWhenExhausted(final boolean blockWhenExhausted) {
+ this.blockWhenExhausted = blockWhenExhausted;
}
-
/**
- * Gets the minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction by the idle object evictor (if any -
- * see {@link #setTimeBetweenEvictionRunsMillis(long)}). When non-positive,
- * no objects will be evicted from the pool due to idle time alone.
- *
- * @return minimum amount of time an object may sit idle in the pool before
- * it is eligible for eviction
+ * Initializes the receiver with the given configuration.
*
- * @see #setMinEvictableIdleTimeMillis
- * @see #setTimeBetweenEvictionRunsMillis
- * @deprecated Use {@link #getMinEvictableIdleTime()}.
+ * @param config Initialization source.
*/
- @Deprecated
- public final long getMinEvictableIdleTimeMillis() {
- return minEvictableIdleTime.toMillis();
+ protected void setConfig(final BaseObjectPoolConfig<T> config) {
+ setLifo(config.getLifo());
+ setMaxWaitMillis(config.getMaxWaitMillis());
+ setBlockWhenExhausted(config.getBlockWhenExhausted());
+ setTestOnCreate(config.getTestOnCreate());
+ setTestOnBorrow(config.getTestOnBorrow());
+ setTestOnReturn(config.getTestOnReturn());
+ setTestWhileIdle(config.getTestWhileIdle());
+ setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun());
+ setMinEvictableIdleTime(config.getMinEvictableIdleTime());
+ setTimeBetweenEvictionRuns(config.getTimeBetweenEvictionRuns());
+ setSoftMinEvictableIdleTime(config.getSoftMinEvictableIdleTime());
+ final EvictionPolicy<T> policy = config.getEvictionPolicy();
+ if (policy == null) {
+ // Use the class name (pre-2.6.0 compatible)
+ setEvictionPolicyClassName(config.getEvictionPolicyClassName());
+ } else {
+ // Otherwise, use the class (2.6.0 feature)
+ setEvictionPolicy(policy);
+ }
+ setEvictorShutdownTimeout(config.getEvictorShutdownTimeout());
}
+
+ // Monitoring (primarily JMX) related methods
+
/**
- * Sets the minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction by the idle object evictor (if any -
- * see {@link #setTimeBetweenEvictionRuns(Duration)}). When non-positive,
- * no objects will be evicted from the pool due to idle time alone.
- *
- * @param minEvictableIdleTimeMillis
- * minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction
+ * Sets the eviction policy for this pool.
*
- * @see #getMinEvictableIdleTime
- * @see #setTimeBetweenEvictionRuns
- * @since 2.10.0
+ * @param evictionPolicy
+ * the eviction policy for this pool.
+ * @since 2.6.0
*/
- public final void setMinEvictableIdleTime(final Duration minEvictableIdleTimeMillis) {
- this.minEvictableIdleTime = minEvictableIdleTimeMillis;
+ public void setEvictionPolicy(final EvictionPolicy<T> evictionPolicy) {
+ this.evictionPolicy = evictionPolicy;
}
/**
- * Sets the minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction by the idle object evictor (if any -
- * see {@link #setTimeBetweenEvictionRunsMillis(long)}). When non-positive,
- * no objects will be evicted from the pool due to idle time alone.
- *
- * @param minEvictableIdleTimeMillis
- * minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction
+ * Sets the eviction policy.
*
- * @see #getMinEvictableIdleTimeMillis
- * @see #setTimeBetweenEvictionRunsMillis
- * @deprecated Use {@link #setMinEvictableIdleTime(Duration)}.
+ * @param className Eviction policy class name.
+ * @param classLoader Load the class from this class loader.
*/
- @Deprecated
- public final void setMinEvictableIdleTimeMillis(final long minEvictableIdleTimeMillis) {
- this.minEvictableIdleTime = Duration.ofMillis(minEvictableIdleTimeMillis);
+ @SuppressWarnings("unchecked")
+ private void setEvictionPolicy(final String className, final ClassLoader classLoader)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ final Class<?> clazz = Class.forName(className, true, classLoader);
+ final Object policy = clazz.getConstructor().newInstance();
+ this.evictionPolicy = (EvictionPolicy<T>) policy;
}
/**
- * Gets the minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction by the idle object evictor (if any -
- * see {@link #setTimeBetweenEvictionRuns(Duration)}),
- * with the extra condition that at least {@code minIdle} object
- * instances remain in the pool. This setting is overridden by
- * {@link #getMinEvictableIdleTime} (that is, if
- * {@link #getMinEvictableIdleTime} is positive, then
- * {@link #getSoftMinEvictableIdleTime} is ignored).
+ * Sets the name of the {@link EvictionPolicy} implementation that is used by this pool. The Pool will attempt to
+ * load the class using the thread context class loader. If that fails, the use the class loader for the
+ * {@link EvictionPolicy} interface.
*
- * @return minimum amount of time an object may sit idle in the pool before
- * it is eligible for eviction if minIdle instances are available
+ * @param evictionPolicyClassName
+ * the fully qualified class name of the new eviction policy
*
- * @see #setSoftMinEvictableIdleTime(Duration)
- * @since 2.10.0
- */
- public final Duration getSoftMinEvictableIdleTime() {
- return softMinEvictableIdleTime;
- }
-
- /**
- * Gets the minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction by the idle object evictor (if any -
- * see {@link #setTimeBetweenEvictionRunsMillis(long)}),
- * with the extra condition that at least {@code minIdle} object
- * instances remain in the pool. This setting is overridden by
- * {@link #getMinEvictableIdleTimeMillis} (that is, if
- * {@link #getMinEvictableIdleTimeMillis} is positive, then
- * {@link #getSoftMinEvictableIdleTimeMillis} is ignored).
- *
- * @return minimum amount of time an object may sit idle in the pool before
- * it is eligible for eviction if minIdle instances are available
- *
- * @see #setSoftMinEvictableIdleTimeMillis
- * @deprecated Use {@link #getSoftMinEvictableIdleTime()}.
- */
- @Deprecated
- public final long getSoftMinEvictableIdleTimeMillis() {
- return softMinEvictableIdleTime.toMillis();
- }
-
- /**
- * Sets the minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction by the idle object evictor (if any -
- * see {@link #setTimeBetweenEvictionRuns(Duration)}),
- * with the extra condition that at least {@code minIdle} object
- * instances remain in the pool. This setting is overridden by
- * {@link #getMinEvictableIdleTime} (that is, if
- * {@link #getMinEvictableIdleTime} is positive, then
- * {@link #getSoftMinEvictableIdleTime} is ignored).
- *
- * @param softMinEvictableIdleTime
- * minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction if minIdle instances are
- * available
- *
- * @see #getSoftMinEvictableIdleTimeMillis
- * @since 2.10.0
- */
- public final void setSoftMinEvictableIdleTime(final Duration softMinEvictableIdleTime) {
- this.softMinEvictableIdleTime = softMinEvictableIdleTime;
- }
-
- /**
- * Sets the minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction by the idle object evictor (if any -
- * see {@link #setTimeBetweenEvictionRunsMillis(long)}),
- * with the extra condition that at least {@code minIdle} object
- * instances remain in the pool. This setting is overridden by
- * {@link #getMinEvictableIdleTimeMillis} (that is, if
- * {@link #getMinEvictableIdleTimeMillis} is positive, then
- * {@link #getSoftMinEvictableIdleTimeMillis} is ignored).
- *
- * @param softMinEvictableIdleTimeMillis
- * minimum amount of time an object may sit idle in the pool
- * before it is eligible for eviction if minIdle instances are
- * available
- *
- * @see #getSoftMinEvictableIdleTimeMillis
- * @deprecated Use {@link #setSoftMinEvictableIdleTime(Duration)}.
- */
- @Deprecated
- public final void setSoftMinEvictableIdleTimeMillis(final long softMinEvictableIdleTimeMillis) {
- this.softMinEvictableIdleTime = Duration.ofMillis(softMinEvictableIdleTimeMillis);
- }
-
- /**
- * Gets the name of the {@link EvictionPolicy} implementation that is
- * used by this pool.
- *
- * @return The fully qualified class name of the {@link EvictionPolicy}
- *
- * @see #setEvictionPolicyClassName(String)
- */
- public final String getEvictionPolicyClassName() {
- return evictionPolicy.getClass().getName();
- }
-
- /**
- * Sets the eviction policy for this pool.
- *
- * @param evictionPolicy
- * the eviction policy for this pool.
- * @since 2.6.0
+ * @see #getEvictionPolicyClassName()
+ * @since 2.6.0 If loading the class using the thread context class loader fails, use the class loader for the
+ * {@link EvictionPolicy} interface.
*/
- public void setEvictionPolicy(final EvictionPolicy<T> evictionPolicy) {
- this.evictionPolicy = evictionPolicy;
+ public final void setEvictionPolicyClassName(final String evictionPolicyClassName) {
+ setEvictionPolicyClassName(evictionPolicyClassName, Thread.currentThread().getContextClassLoader());
}
/**
@@ -774,63 +1107,6 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Sets the eviction policy.
- *
- * @param className Eviction policy class name.
- * @param classLoader Load the class from this class loader.
- */
- @SuppressWarnings("unchecked")
- private void setEvictionPolicy(final String className, final ClassLoader classLoader)
- throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
- final Class<?> clazz = Class.forName(className, true, classLoader);
- final Object policy = clazz.getConstructor().newInstance();
- this.evictionPolicy = (EvictionPolicy<T>) policy;
- }
-
- /**
- * Sets the name of the {@link EvictionPolicy} implementation that is used by this pool. The Pool will attempt to
- * load the class using the thread context class loader. If that fails, the use the class loader for the
- * {@link EvictionPolicy} interface.
- *
- * @param evictionPolicyClassName
- * the fully qualified class name of the new eviction policy
- *
- * @see #getEvictionPolicyClassName()
- * @since 2.6.0 If loading the class using the thread context class loader fails, use the class loader for the
- * {@link EvictionPolicy} interface.
- */
- public final void setEvictionPolicyClassName(final String evictionPolicyClassName) {
- setEvictionPolicyClassName(evictionPolicyClassName, Thread.currentThread().getContextClassLoader());
- }
-
- /**
- * Gets the timeout that will be used when waiting for the Evictor to
- * shutdown if this pool is closed and it is the only pool still using the
- * the value for the Evictor.
- *
- * @return The timeout in milliseconds that will be used while waiting for
- * the Evictor to shut down.
- * @deprecated Use {@link #getEvictorShutdownTimeout()}.
- */
- @Deprecated
- public final long getEvictorShutdownTimeoutMillis() {
- return evictorShutdownTimeout.toMillis();
- }
-
- /**
- * Gets the timeout that will be used when waiting for the Evictor to
- * shutdown if this pool is closed and it is the only pool still using the
- * the value for the Evictor.
- *
- * @return The timeout that will be used while waiting for
- * the Evictor to shut down.
- * @since 2.10.0
- */
- public final Duration getEvictorShutdownTimeout() {
- return evictorShutdownTimeout;
- }
-
- /**
* Sets the timeout that will be used when waiting for the Evictor to shutdown if this pool is closed and it is the
* only pool still using the the value for the Evictor.
*
@@ -856,232 +1132,154 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Closes the pool, destroys the remaining idle objects and, if registered
- * in JMX, deregisters it.
+ * Sets whether the pool has LIFO (last in, first out) behavior with
+ * respect to idle objects - always returning the most recently used object
+ * from the pool, or as a FIFO (first in, first out) queue, where the pool
+ * always returns the oldest object in the idle object pool.
+ *
+ * @param lifo {@code true} if the pool is to be configured with LIFO
+ * behavior or {@code false} if the pool is to be
+ * configured with FIFO behavior
+ *
+ * @see #getLifo()
*/
- public abstract void close();
+ public final void setLifo(final boolean lifo) {
+ this.lifo = lifo;
+ }
/**
- * Has this pool instance been closed.
- * @return {@code true} when this pool has been closed.
+ * Sets the cap on the number of objects that can be allocated by the pool
+ * (checked out to clients, or idle awaiting checkout) at a given time. Use
+ * a negative value for no limit.
+ *
+ * @param maxTotal The cap on the total number of object instances managed
+ * by the pool. Negative values mean that there is no limit
+ * to the number of objects allocated by the pool.
+ *
+ * @see #getMaxTotal
*/
- public final boolean isClosed() {
- return closed;
+ public final void setMaxTotal(final int maxTotal) {
+ this.maxTotal = maxTotal;
}
/**
- * <p>Perform {@code numTests} idle object eviction tests, evicting
- * examined objects that meet the criteria for eviction. If
- * {@code testWhileIdle} is true, examined objects are validated
- * when visited (and removed if invalid); otherwise only objects that
- * have been idle for more than {@code minEvicableIdleTimeMillis}
- * are removed.</p>
+ * Sets the maximum amount of time (in milliseconds) the
+ * {@code borrowObject()} method should block before throwing an
+ * exception when the pool is exhausted and
+ * {@link #getBlockWhenExhausted} is true. When less than 0, the
+ * {@code borrowObject()} method may block indefinitely.
*
- * @throws Exception when there is a problem evicting idle objects.
+ * @param maxWaitMillis the maximum number of milliseconds
+ * {@code borrowObject()} will block or negative
+ * for indefinitely.
+ *
+ * @see #getMaxWaitMillis
+ * @see #setBlockWhenExhausted
*/
- public abstract void evict() throws Exception;
+ public final void setMaxWaitMillis(final long maxWaitMillis) {
+ this.maxWait = Duration.ofMillis(maxWaitMillis);
+ }
/**
- * Gets the {@link EvictionPolicy} defined for this pool.
+ * Sets the minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction by the idle object evictor (if any -
+ * see {@link #setTimeBetweenEvictionRuns(Duration)}). When non-positive,
+ * no objects will be evicted from the pool due to idle time alone.
*
- * @return the eviction policy
- * @since 2.4
- * @since 2.6.0 Changed access from protected to public.
+ * @param minEvictableIdleTimeMillis
+ * minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction
+ *
+ * @see #getMinEvictableIdleTime
+ * @see #setTimeBetweenEvictionRuns
+ * @since 2.10.0
*/
- public EvictionPolicy<T> getEvictionPolicy() {
- return evictionPolicy;
+ public final void setMinEvictableIdleTime(final Duration minEvictableIdleTimeMillis) {
+ this.minEvictableIdleTime = minEvictableIdleTimeMillis;
}
/**
- * Verifies that the pool is open.
- * @throws IllegalStateException if the pool is closed.
+ * Sets the minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction by the idle object evictor (if any -
+ * see {@link #setTimeBetweenEvictionRunsMillis(long)}). When non-positive,
+ * no objects will be evicted from the pool due to idle time alone.
+ *
+ * @param minEvictableIdleTimeMillis
+ * minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction
+ *
+ * @see #getMinEvictableIdleTimeMillis
+ * @see #setTimeBetweenEvictionRunsMillis
+ * @deprecated Use {@link #setMinEvictableIdleTime(Duration)}.
*/
- final void assertOpen() throws IllegalStateException {
- if (isClosed()) {
- throw new IllegalStateException("Pool not open");
- }
+ @Deprecated
+ public final void setMinEvictableIdleTimeMillis(final long minEvictableIdleTimeMillis) {
+ this.minEvictableIdleTime = Duration.ofMillis(minEvictableIdleTimeMillis);
}
/**
- * <p>Starts the evictor with the given delay. If there is an evictor
- * running when this method is called, it is stopped and replaced with a
- * new evictor with the specified delay.</p>
+ * Sets the maximum number of objects to examine during each run (if any)
+ * of the idle object evictor thread. When positive, the number of tests
+ * performed for a run will be the minimum of the configured value and the
+ * number of idle instances in the pool. When negative, the number of tests
+ * performed will be <code>ceil({@link #getNumIdle}/
+ * abs({@link #getNumTestsPerEvictionRun}))</code> which means that when the
+ * value is {@code -n} roughly one nth of the idle objects will be
+ * tested per run.
*
- * <p>This method needs to be final, since it is called from a constructor.
- * See POOL-195.</p>
+ * @param numTestsPerEvictionRun
+ * max number of objects to examine during each evictor run
*
- * @param delay time in milliseconds before start and between eviction runs
- */
- final void startEvictor(final Duration delay) {
- synchronized (evictionLock) {
- final boolean isPositiverDelay = !delay.isNegative() && !delay.isZero();
- if (evictor == null) { // Starting evictor for the first time or after a cancel
- if (isPositiverDelay) { // Starting new evictor
- evictor = new Evictor();
- EvictionTimer.schedule(evictor, delay, delay);
- }
- } else { // Stop or restart of existing evictor
- if (isPositiverDelay) { // Restart
- synchronized (EvictionTimer.class) { // Ensure no cancel can happen between cancel / schedule calls
- EvictionTimer.cancel(evictor, evictorShutdownTimeout, true);
- evictor = null;
- evictionIterator = null;
- evictor = new Evictor();
- EvictionTimer.schedule(evictor, delay, delay);
- }
- } else { // Stopping evictor
- EvictionTimer.cancel(evictor, evictorShutdownTimeout, false);
- }
- }
- }
- }
-
- /**
- * Stops the evictor.
- */
- void stopEvictor() {
- startEvictor(Duration.ofMillis(-1L));
- }
- /**
- * Tries to ensure that the configured minimum number of idle instances are
- * available in the pool.
- * @throws Exception if an error occurs creating idle instances
- */
- abstract void ensureMinIdle() throws Exception;
-
-
- // Monitoring (primarily JMX) related methods
-
- /**
- * Provides the name under which the pool has been registered with the
- * platform MBean server or {@code null} if the pool has not been
- * registered.
- * @return the JMX name
- */
- public final ObjectName getJmxName() {
- return objectName;
- }
-
- /**
- * Provides the stack trace for the call that created this pool. JMX
- * registration may trigger a memory leak so it is important that pools are
- * deregistered when no longer used by calling the {@link #close()} method.
- * This method is provided to assist with identifying code that creates but
- * does not close it thereby creating a memory leak.
- * @return pool creation stack trace
- */
- public final String getCreationStackTrace() {
- return creationStackTrace;
- }
-
- /**
- * The total number of objects successfully borrowed from this pool over the
- * lifetime of the pool.
- * @return the borrowed object count
- */
- public final long getBorrowedCount() {
- return borrowedCount.get();
- }
-
- /**
- * The total number of objects returned to this pool over the lifetime of
- * the pool. This excludes attempts to return the same object multiple
- * times.
- * @return the returned object count
- */
- public final long getReturnedCount() {
- return returnedCount.get();
- }
-
- /**
- * The total number of objects created for this pool over the lifetime of
- * the pool.
- * @return the created object count
- */
- public final long getCreatedCount() {
- return createdCount.get();
- }
-
- /**
- * The total number of objects destroyed by this pool over the lifetime of
- * the pool.
- * @return the destroyed object count
- */
- public final long getDestroyedCount() {
- return destroyedCount.get();
- }
-
- /**
- * The total number of objects destroyed by the evictor associated with this
- * pool over the lifetime of the pool.
- * @return the evictor destroyed object count
- */
- public final long getDestroyedByEvictorCount() {
- return destroyedByEvictorCount.get();
- }
-
- /**
- * The total number of objects destroyed by this pool as a result of failing
- * validation during {@code borrowObject()} over the lifetime of the
- * pool.
- * @return validation destroyed object count
- */
- public final long getDestroyedByBorrowValidationCount() {
- return destroyedByBorrowValidationCount.get();
- }
-
- /**
- * The mean time objects are active for based on the last {@link
- * #MEAN_TIMING_STATS_CACHE_SIZE} objects returned to the pool.
- * @return mean time an object has been checked out from the pool among
- * recently returned objects
- */
- public final long getMeanActiveTimeMillis() {
- return activeTimes.getMean();
- }
-
- /**
- * The mean time objects are idle for based on the last {@link
- * #MEAN_TIMING_STATS_CACHE_SIZE} objects borrowed from the pool.
- * @return mean time an object has been idle in the pool among recently
- * borrowed objects
- */
- public final long getMeanIdleTimeMillis() {
- return idleTimes.getMean();
- }
-
- /**
- * The mean time threads wait to borrow an object based on the last {@link
- * #MEAN_TIMING_STATS_CACHE_SIZE} objects borrowed from the pool.
- * @return mean time in milliseconds that a recently served thread has had
- * to wait to borrow an object from the pool
+ * @see #getNumTestsPerEvictionRun
+ * @see #setTimeBetweenEvictionRunsMillis
*/
- public final long getMeanBorrowWaitTimeMillis() {
- return waitTimes.getMean();
+ public final void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) {
+ this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
- * The maximum time a thread has waited to borrow objects from the pool.
- * @return maximum wait time in milliseconds since the pool was created
+ * Sets the minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction by the idle object evictor (if any -
+ * see {@link #setTimeBetweenEvictionRuns(Duration)}),
+ * with the extra condition that at least {@code minIdle} object
+ * instances remain in the pool. This setting is overridden by
+ * {@link #getMinEvictableIdleTime} (that is, if
+ * {@link #getMinEvictableIdleTime} is positive, then
+ * {@link #getSoftMinEvictableIdleTime} is ignored).
+ *
+ * @param softMinEvictableIdleTime
+ * minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction if minIdle instances are
+ * available
+ *
+ * @see #getSoftMinEvictableIdleTimeMillis
+ * @since 2.10.0
*/
- public final long getMaxBorrowWaitTimeMillis() {
- return maxBorrowWaitTimeMillis.get();
+ public final void setSoftMinEvictableIdleTime(final Duration softMinEvictableIdleTime) {
+ this.softMinEvictableIdleTime = softMinEvictableIdleTime;
}
/**
- * The number of instances currently idle in this pool.
- * @return count of instances available for checkout from the pool
- */
- public abstract int getNumIdle();
-
- /**
- * The listener used (if any) to receive notifications of exceptions
- * unavoidably swallowed by the pool.
+ * Sets the minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction by the idle object evictor (if any -
+ * see {@link #setTimeBetweenEvictionRunsMillis(long)}),
+ * with the extra condition that at least {@code minIdle} object
+ * instances remain in the pool. This setting is overridden by
+ * {@link #getMinEvictableIdleTimeMillis} (that is, if
+ * {@link #getMinEvictableIdleTimeMillis} is positive, then
+ * {@link #getSoftMinEvictableIdleTimeMillis} is ignored).
*
- * @return The listener or {@code null} for no listener
+ * @param softMinEvictableIdleTimeMillis
+ * minimum amount of time an object may sit idle in the pool
+ * before it is eligible for eviction if minIdle instances are
+ * available
+ *
+ * @see #getSoftMinEvictableIdleTimeMillis
+ * @deprecated Use {@link #setSoftMinEvictableIdleTime(Duration)}.
*/
- public final SwallowedExceptionListener getSwallowedExceptionListener() {
- return swallowedExceptionListener;
+ @Deprecated
+ public final void setSoftMinEvictableIdleTimeMillis(final long softMinEvictableIdleTimeMillis) {
+ this.softMinEvictableIdleTime = Duration.ofMillis(softMinEvictableIdleTimeMillis);
}
/**
@@ -1097,406 +1295,178 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
- * Swallows an exception and notifies the configured listener for swallowed
- * exceptions queue.
- *
- * @param swallowException exception to be swallowed
- */
- final void swallowException(final Exception swallowException) {
- final SwallowedExceptionListener listener = getSwallowedExceptionListener();
-
- if (listener == null) {
- return;
- }
-
- try {
- listener.onSwallowException(swallowException);
- } catch (final VirtualMachineError e) {
- throw e;
- } catch (final Throwable t) {
- // Ignore. Enjoy the irony.
- }
- }
-
- /**
- * Updates statistics after an object is borrowed from the pool.
- * @param p object borrowed from the pool
- * @param waitTime time (in milliseconds) that the borrowing thread had to wait
- */
- final void updateStatsBorrow(final PooledObject<T> p, final long waitTime) {
- borrowedCount.incrementAndGet();
- idleTimes.add(p.getIdleTimeMillis());
- waitTimes.add(waitTime);
-
- // lock-free optimistic-locking maximum
- long currentMax;
- do {
- currentMax = maxBorrowWaitTimeMillis.get();
- if (currentMax >= waitTime) {
- break;
- }
- } while (!maxBorrowWaitTimeMillis.compareAndSet(currentMax, waitTime));
- }
-
- /**
- * Updates statistics after an object is returned to the pool.
- * @param activeTime the amount of time (in milliseconds) that the returning
- * object was checked out
- */
- final void updateStatsReturn(final long activeTime) {
- returnedCount.incrementAndGet();
- activeTimes.add(activeTime);
- }
-
- /**
- * Marks the object as returning to the pool.
- * @param pooledObject instance to return to the keyed pool
- */
- protected void markReturningState(final PooledObject<T> pooledObject) {
- synchronized(pooledObject) {
- final PooledObjectState state = pooledObject.getState();
- if (state != PooledObjectState.ALLOCATED) {
- throw new IllegalStateException(
- "Object has already been returned to this pool or is invalid");
- }
- pooledObject.markReturning(); // Keep from being marked abandoned
- }
- }
-
- /**
- * Unregisters this pool's MBean.
- */
- final void jmxUnregister() {
- if (objectName != null) {
- try {
- ManagementFactory.getPlatformMBeanServer().unregisterMBean(
- objectName);
- } catch (final MBeanRegistrationException | InstanceNotFoundException e) {
- swallowException(e);
- }
- }
- }
-
- /**
- * Registers the pool with the platform MBean server.
- * The registered name will be
- * {@code jmxNameBase + jmxNamePrefix + i} where i is the least
- * integer greater than or equal to 1 such that the name is not already
- * registered. Swallows MBeanRegistrationException, NotCompliantMBeanException
- * returning null.
- *
- * @param config Pool configuration
- * @param jmxNameBase default base JMX name for this pool
- * @param jmxNamePrefix name prefix
- * @return registered ObjectName, null if registration fails
- */
- private ObjectName jmxRegister(final BaseObjectPoolConfig<T> config,
- final String jmxNameBase, String jmxNamePrefix) {
- ObjectName newObjectName = null;
- final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
- int i = 1;
- boolean registered = false;
- String base = config.getJmxNameBase();
- if (base == null) {
- base = jmxNameBase;
- }
- while (!registered) {
- try {
- ObjectName objName;
- // Skip the numeric suffix for the first pool in case there is
- // only one so the names are cleaner.
- if (i == 1) {
- objName = new ObjectName(base + jmxNamePrefix);
- } else {
- objName = new ObjectName(base + jmxNamePrefix + i);
- }
- mbs.registerMBean(this, objName);
- newObjectName = objName;
- registered = true;
- } catch (final MalformedObjectNameException e) {
- if (BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX.equals(
- jmxNamePrefix) && jmxNameBase.equals(base)) {
- // Shouldn't happen. Skip registration if it does.
- registered = true;
- } else {
- // Must be an invalid name. Use the defaults instead.
- jmxNamePrefix =
- BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX;
- base = jmxNameBase;
- }
- } catch (final InstanceAlreadyExistsException e) {
- // Increment the index and try again
- i++;
- } catch (final MBeanRegistrationException | NotCompliantMBeanException e) {
- // Shouldn't happen. Skip registration if it does.
- registered = true;
- }
- }
- return newObjectName;
- }
-
- /**
- * Gets the stack trace of an exception as a string.
- * @param e exception to trace
- * @return exception stack trace as a string
- */
- private String getStackTrace(final Exception e) {
- // Need the exception in string form to prevent the retention of
- // references to classes in the stack trace that could trigger a memory
- // leak in a container environment.
- final Writer w = new StringWriter();
- final PrintWriter pw = new PrintWriter(w);
- e.printStackTrace(pw);
- return w.toString();
- }
-
- // Inner classes
-
- /**
- * The idle object evictor {@link TimerTask}.
- *
- * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis
- */
- class Evictor implements Runnable {
-
- private ScheduledFuture<?> scheduledFuture;
-
- /**
- * Run pool maintenance. Evict objects qualifying for eviction and then
- * ensure that the minimum number of idle instances are available.
- * Since the Timer that invokes Evictors is shared for all Pools but
- * pools may exist in different class loaders, the Evictor ensures that
- * any actions taken are under the class loader of the factory
- * associated with the pool.
- */
- @Override
- public void run() {
- final ClassLoader savedClassLoader =
- Thread.currentThread().getContextClassLoader();
- try {
- if (factoryClassLoader != null) {
- // Set the class loader for the factory
- final ClassLoader cl = factoryClassLoader.get();
- if (cl == null) {
- // The pool has been dereferenced and the class loader
- // GC'd. Cancel this timer so the pool can be GC'd as
- // well.
- cancel();
- return;
- }
- Thread.currentThread().setContextClassLoader(cl);
- }
-
- // Evict from the pool
- try {
- evict();
- } catch(final Exception e) {
- swallowException(e);
- } catch(final OutOfMemoryError oome) {
- // Log problem but give evictor thread a chance to continue
- // in case error is recoverable
- oome.printStackTrace(System.err);
- }
- // Re-create idle instances.
- try {
- ensureMinIdle();
- } catch (final Exception e) {
- swallowException(e);
- }
- } finally {
- // Restore the previous CCL
- Thread.currentThread().setContextClassLoader(savedClassLoader);
- }
- }
-
-
- /**
- * Sets the scheduled future.
- *
- * @param scheduledFuture the scheduled future.
- */
- void setScheduledFuture(final ScheduledFuture<?> scheduledFuture) {
- this.scheduledFuture = scheduledFuture;
- }
-
-
- /**
- * Cancels the scheduled future.
- */
- void cancel() {
- scheduledFuture.cancel(false);
- }
-
- }
-
- /**
- * Maintains a cache of values for a single metric and reports
- * statistics on the cached values.
- */
- private class StatsStore {
-
- private final AtomicLong values[];
- private final int size;
- private int index;
-
- /**
- * Create a StatsStore with the given cache size.
- *
- * @param size number of values to maintain in the cache.
- */
- public StatsStore(final int size) {
- this.size = size;
- values = new AtomicLong[size];
- for (int i = 0; i < size; i++) {
- values[i] = new AtomicLong(-1);
- }
- }
-
- /**
- * Adds a value to the cache. If the cache is full, one of the
- * existing values is replaced by the new value.
- *
- * @param value new value to add to the cache.
- */
- public synchronized void add(final long value) {
- values[index].set(value);
- index++;
- if (index == size) {
- index = 0;
- }
- }
-
- /**
- * Gets the mean of the cached values.
- *
- * @return the mean of the cache, truncated to long
- */
- public long getMean() {
- double result = 0;
- int counter = 0;
- for (int i = 0; i < size; i++) {
- final long value = values[i].get();
- if (value != -1) {
- counter++;
- result = result * ((counter - 1) / (double) counter) +
- value/(double) counter;
- }
- }
- return (long) result;
- }
-
- @Override
- public String toString() {
- final StringBuilder builder = new StringBuilder();
- builder.append("StatsStore [values=");
- builder.append(Arrays.toString(values));
- builder.append(", size=");
- builder.append(size);
- builder.append(", index=");
- builder.append(index);
- builder.append("]");
- return builder.toString();
- }
+ * Sets whether objects borrowed from the pool will be validated before
+ * being returned from the {@code borrowObject()} method. Validation is
+ * performed by the {@code validateObject()} method of the factory
+ * associated with the pool. If the object fails to validate, it will be
+ * removed from the pool and destroyed, and a new attempt will be made to
+ * borrow an object from the pool.
+ *
+ * @param testOnBorrow {@code true} if objects should be validated
+ * before being returned from the
+ * {@code borrowObject()} method
+ *
+ * @see #getTestOnBorrow
+ */
+ public final void setTestOnBorrow(final boolean testOnBorrow) {
+ this.testOnBorrow = testOnBorrow;
}
/**
- * The idle object eviction iterator. Holds a reference to the idle objects.
+ * Sets whether objects created for the pool will be validated before
+ * being returned from the {@code borrowObject()} method. Validation is
+ * performed by the {@code validateObject()} method of the factory
+ * associated with the pool. If the object fails to validate, then
+ * {@code borrowObject()} will fail.
+ *
+ * @param testOnCreate {@code true} if newly created objects should be
+ * validated before being returned from the
+ * {@code borrowObject()} method
+ *
+ * @see #getTestOnCreate
+ *
+ * @since 2.2
*/
- class EvictionIterator implements Iterator<PooledObject<T>> {
-
- private final Deque<PooledObject<T>> idleObjects;
- private final Iterator<PooledObject<T>> idleObjectIterator;
-
- /**
- * Create an EvictionIterator for the provided idle instance deque.
- * @param idleObjects underlying deque
- */
- EvictionIterator(final Deque<PooledObject<T>> idleObjects) {
- this.idleObjects = idleObjects;
-
- if (getLifo()) {
- idleObjectIterator = idleObjects.descendingIterator();
- } else {
- idleObjectIterator = idleObjects.iterator();
- }
- }
-
- /**
- * Gets the idle object deque referenced by this iterator.
- * @return the idle object deque
- */
- public Deque<PooledObject<T>> getIdleObjects() {
- return idleObjects;
- }
-
- /** {@inheritDoc} */
- @Override
- public boolean hasNext() {
- return idleObjectIterator.hasNext();
- }
+ public final void setTestOnCreate(final boolean testOnCreate) {
+ this.testOnCreate = testOnCreate;
+ }
- /** {@inheritDoc} */
- @Override
- public PooledObject<T> next() {
- return idleObjectIterator.next();
- }
+ /**
+ * Sets whether objects borrowed from the pool will be validated when
+ * they are returned to the pool via the {@code returnObject()} method.
+ * Validation is performed by the {@code validateObject()} method of
+ * the factory associated with the pool. Returning objects that fail validation
+ * are destroyed rather then being returned the pool.
+ *
+ * @param testOnReturn {@code true} if objects are validated on
+ * return to the pool via the
+ * {@code returnObject()} method
+ *
+ * @see #getTestOnReturn
+ */
+ public final void setTestOnReturn(final boolean testOnReturn) {
+ this.testOnReturn = testOnReturn;
+ }
- /** {@inheritDoc} */
- @Override
- public void remove() {
- idleObjectIterator.remove();
- }
+ /**
+ * Sets whether objects sitting idle in the pool will be validated by the
+ * idle object evictor (if any - see
+ * {@link #setTimeBetweenEvictionRuns(Duration)}). Validation is performed
+ * by the {@code validateObject()} method of the factory associated
+ * with the pool. If the object fails to validate, it will be removed from
+ * the pool and destroyed. Note that setting this property has no effect
+ * unless the idle object evictor is enabled by setting
+ * {@code timeBetweenEvictionRunsMillis} to a positive value.
+ *
+ * @param testWhileIdle
+ * {@code true} so objects will be validated by the evictor
+ *
+ * @see #getTestWhileIdle
+ * @see #setTimeBetweenEvictionRuns
+ */
+ public final void setTestWhileIdle(final boolean testWhileIdle) {
+ this.testWhileIdle = testWhileIdle;
+ }
+ /**
+ * Sets the number of milliseconds to sleep between runs of the idle object evictor thread.
+ * <ul>
+ * <li>When positive, the idle object evictor thread starts.</li>
+ * <li>When non-positive, no idle object evictor thread runs.</li>
+ * </ul>
+ *
+ * @param timeBetweenEvictionRuns
+ * duration to sleep between evictor runs
+ *
+ * @see #getTimeBetweenEvictionRunsMillis
+ * @since 2.10.0
+ */
+ public final void setTimeBetweenEvictionRuns(final Duration timeBetweenEvictionRuns) {
+ this.timeBetweenEvictionRuns = timeBetweenEvictionRuns;
+ startEvictor(this.timeBetweenEvictionRuns);
}
/**
- * Wrapper for objects under management by the pool.
+ * Sets the number of milliseconds to sleep between runs of the idle object evictor thread.
+ * <ul>
+ * <li>When positive, the idle object evictor thread starts.</li>
+ * <li>When non-positive, no idle object evictor thread runs.</li>
+ * </ul>
*
- * GenericObjectPool and GenericKeyedObjectPool maintain references to all
- * objects under management using maps keyed on the objects. This wrapper
- * class ensures that objects can work as hash keys.
+ * @param timeBetweenEvictionRunsMillis
+ * number of milliseconds to sleep between evictor runs
*
- * @param <T> type of objects in the pool
+ * @see #getTimeBetweenEvictionRunsMillis
+ * @deprecated Use {@link #setTimeBetweenEvictionRuns(Duration)}.
*/
- static class IdentityWrapper<T> {
- /** Wrapped object */
- private final T instance;
+ @Deprecated
+ public final void setTimeBetweenEvictionRunsMillis(final long timeBetweenEvictionRunsMillis) {
+ this.timeBetweenEvictionRuns = Duration.ofMillis(timeBetweenEvictionRunsMillis);
+ startEvictor(timeBetweenEvictionRuns);
+ }
- /**
- * Create a wrapper for an instance.
- *
- * @param instance object to wrap
- */
- public IdentityWrapper(final T instance) {
- this.instance = instance;
+ /**
+ * <p>Starts the evictor with the given delay. If there is an evictor
+ * running when this method is called, it is stopped and replaced with a
+ * new evictor with the specified delay.</p>
+ *
+ * <p>This method needs to be final, since it is called from a constructor.
+ * See POOL-195.</p>
+ *
+ * @param delay time in milliseconds before start and between eviction runs
+ */
+ final void startEvictor(final Duration delay) {
+ synchronized (evictionLock) {
+ final boolean isPositiverDelay = !delay.isNegative() && !delay.isZero();
+ if (evictor == null) { // Starting evictor for the first time or after a cancel
+ if (isPositiverDelay) { // Starting new evictor
+ evictor = new Evictor();
+ EvictionTimer.schedule(evictor, delay, delay);
+ }
+ } else { // Stop or restart of existing evictor
+ if (isPositiverDelay) { // Restart
+ synchronized (EvictionTimer.class) { // Ensure no cancel can happen between cancel / schedule calls
+ EvictionTimer.cancel(evictor, evictorShutdownTimeout, true);
+ evictor = null;
+ evictionIterator = null;
+ evictor = new Evictor();
+ EvictionTimer.schedule(evictor, delay, delay);
+ }
+ } else { // Stopping evictor
+ EvictionTimer.cancel(evictor, evictorShutdownTimeout, false);
+ }
+ }
}
+ }
- @Override
- public int hashCode() {
- return System.identityHashCode(instance);
- }
+ // Inner classes
- @Override
- @SuppressWarnings("rawtypes")
- public boolean equals(final Object other) {
- return other instanceof IdentityWrapper &&
- ((IdentityWrapper) other).instance == instance;
- }
+ /**
+ * Stops the evictor.
+ */
+ void stopEvictor() {
+ startEvictor(Duration.ofMillis(-1L));
+ }
- /**
- * @return the wrapped object
- */
- public T getObject() {
- return instance;
+ /**
+ * Swallows an exception and notifies the configured listener for swallowed
+ * exceptions queue.
+ *
+ * @param swallowException exception to be swallowed
+ */
+ final void swallowException(final Exception swallowException) {
+ final SwallowedExceptionListener listener = getSwallowedExceptionListener();
+
+ if (listener == null) {
+ return;
}
- @Override
- public String toString() {
- final StringBuilder builder = new StringBuilder();
- builder.append("IdentityWrapper [instance=");
- builder.append(instance);
- builder.append("]");
- return builder.toString();
+ try {
+ listener.onSwallowException(swallowException);
+ } catch (final VirtualMachineError e) {
+ throw e;
+ } catch (final Throwable t) {
+ // Ignore. Enjoy the irony.
}
}
@@ -1570,5 +1540,35 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
builder.append(swallowedExceptionListener);
}
+ /**
+ * Updates statistics after an object is borrowed from the pool.
+ * @param p object borrowed from the pool
+ * @param waitTime time (in milliseconds) that the borrowing thread had to wait
+ */
+ final void updateStatsBorrow(final PooledObject<T> p, final long waitTime) {
+ borrowedCount.incrementAndGet();
+ idleTimes.add(p.getIdleTimeMillis());
+ waitTimes.add(waitTime);
+
+ // lock-free optimistic-locking maximum
+ long currentMax;
+ do {
+ currentMax = maxBorrowWaitTimeMillis.get();
+ if (currentMax >= waitTime) {
+ break;
+ }
+ } while (!maxBorrowWaitTimeMillis.compareAndSet(currentMax, waitTime));
+ }
+
+ /**
+ * Updates statistics after an object is returned to the pool.
+ * @param activeTime the amount of time (in milliseconds) that the returning
+ * object was checked out
+ */
+ final void updateStatsReturn(final long activeTime) {
+ returnedCount.incrementAndGet();
+ activeTimes.add(activeTime);
+ }
+
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java b/src/main/java/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java
index 9147725..8798675 100644
--- a/src/main/java/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java
+++ b/src/main/java/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java
@@ -258,17 +258,77 @@ public abstract class BaseObjectPoolConfig<T> extends BaseObject implements Clon
/**
- * Gets the value for the {@code lifo} configuration attribute for pools
- * created with this configuration instance.
+ * Gets the value for the {@code blockWhenExhausted} configuration attribute
+ * for pools created with this configuration instance.
*
- * @return The current setting of {@code lifo} for this configuration
- * instance
+ * @return The current setting of {@code blockWhenExhausted} for this
+ * configuration instance
*
- * @see GenericObjectPool#getLifo()
- * @see GenericKeyedObjectPool#getLifo()
+ * @see GenericObjectPool#getBlockWhenExhausted()
+ * @see GenericKeyedObjectPool#getBlockWhenExhausted()
*/
- public boolean getLifo() {
- return lifo;
+ public boolean getBlockWhenExhausted() {
+ return blockWhenExhausted;
+ }
+
+ /**
+ * Gets the value for the {@code evictionPolicyClass} configuration
+ * attribute for pools created with this configuration instance.
+ *
+ * @return The current setting of {@code evictionPolicyClass} for this
+ * configuration instance
+ *
+ * @see GenericObjectPool#getEvictionPolicy()
+ * @see GenericKeyedObjectPool#getEvictionPolicy()
+ * @since 2.6.0
+ */
+ public EvictionPolicy<T> getEvictionPolicy() {
+ return evictionPolicy;
+ }
+
+ /**
+ * Gets the value for the {@code evictionPolicyClassName} configuration
+ * attribute for pools created with this configuration instance.
+ *
+ * @return The current setting of {@code evictionPolicyClassName} for this
+ * configuration instance
+ *
+ * @see GenericObjectPool#getEvictionPolicyClassName()
+ * @see GenericKeyedObjectPool#getEvictionPolicyClassName()
+ */
+ public String getEvictionPolicyClassName() {
+ return evictionPolicyClassName;
+ }
+
+ /**
+ * Gets the value for the {@code evictorShutdownTimeout} configuration
+ * attribute for pools created with this configuration instance.
+ *
+ * @return The current setting of {@code evictorShutdownTimeout} for
+ * this configuration instance
+ *
+ * @see GenericObjectPool#getEvictorShutdownTimeout()
+ * @see GenericKeyedObjectPool#getEvictorShutdownTimeout()
+ * @since 2.10.0
+ */
+ public Duration getEvictorShutdownTimeout() {
+ return evictorShutdownTimeout;
+ }
+
+ /**
+ * Gets the value for the {@code evictorShutdownTimeout} configuration
+ * attribute for pools created with this configuration instance.
+ *
+ * @return The current setting of {@code evictorShutdownTimeout} for
+ * this configuration instance
+ *
+ * @see GenericObjectPool#getEvictorShutdownTimeoutMillis()
+ * @see GenericKeyedObjectPool#getEvictorShutdownTimeoutMillis()
+ * @deprecated Use {@link #getEvictorShutdownTimeout()}.
+ */
+ @Deprecated
+ public long getEvictorShutdownTimeoutMillis() {
+ return evictorShutdownTimeout.toMillis();
}
/**
@@ -286,59 +346,67 @@ public abstract class BaseObjectPoolConfig<T> extends BaseObject implements Clon
}
/**
- * Sets the value for the {@code lifo} configuration attribute for pools
- * created with this configuration instance.
- *
- * @param lifo The new setting of {@code lifo}
- * for this configuration instance
+ * Gets the value of the flag that determines if JMX will be enabled for
+ * pools created with this configuration instance.
*
- * @see GenericObjectPool#getLifo()
- * @see GenericKeyedObjectPool#getLifo()
+ * @return The current setting of {@code jmxEnabled} for this configuration
+ * instance
*/
- public void setLifo(final boolean lifo) {
- this.lifo = lifo;
+ public boolean getJmxEnabled() {
+ return jmxEnabled;
}
/**
- * Sets the value for the {@code fairness} configuration attribute for pools
- * created with this configuration instance.
+ * Gets the value of the JMX name base that will be used as part of the
+ * name assigned to JMX enabled pools created with this configuration
+ * instance. A value of {@code null} means that the pool will define
+ * the JMX name base.
*
- * @param fairness The new setting of {@code fairness}
- * for this configuration instance
+ * @return The current setting of {@code jmxNameBase} for this
+ * configuration instance
+ */
+ public String getJmxNameBase() {
+ return jmxNameBase;
+ }
+
+ /**
+ * Gets the value of the JMX name prefix that will be used as part of the
+ * name assigned to JMX enabled pools created with this configuration
+ * instance.
*
- * @see GenericObjectPool#getFairness()
- * @see GenericKeyedObjectPool#getFairness()
+ * @return The current setting of {@code jmxNamePrefix} for this
+ * configuration instance
*/
- public void setFairness(final boolean fairness) {
- this.fairness = fairness;
+ public String getJmxNamePrefix() {
+ return jmxNamePrefix;
}
/**
- * Gets the value for the {@code maxWait} configuration attribute for pools
+ * Gets the value for the {@code lifo} configuration attribute for pools
* created with this configuration instance.
*
- * @return The current setting of {@code maxWait} for this
- * configuration instance
+ * @return The current setting of {@code lifo} for this configuration
+ * instance
*
- * @see GenericObjectPool#getMaxWaitMillis()
- * @see GenericKeyedObjectPool#getMaxWaitMillis()
+ * @see GenericObjectPool#getLifo()
+ * @see GenericKeyedObjectPool#getLifo()
*/
- public long getMaxWaitMillis() {
- return maxWaitMillis.toMillis();
+ public boolean getLifo() {
+ return lifo;
}
/**
- * Sets the value for the {@code maxWait} configuration attribute for pools
+ * Gets the value for the {@code maxWait} configuration attribute for pools
* created with this configuration instance.
*
- * @param maxWaitMillis The new setting of {@code maxWaitMillis}
- * for this configuration instance
+ * @return The current setting of {@code maxWait} for this
+ * configuration instance
*
* @see GenericObjectPool#getMaxWaitMillis()
* @see GenericKeyedObjectPool#getMaxWaitMillis()
*/
- public void setMaxWaitMillis(final long maxWaitMillis) {
- this.maxWaitMillis = Duration.ofMillis(maxWaitMillis);
+ public long getMaxWaitMillis() {
+ return maxWaitMillis.toMillis();
}
/**
@@ -373,34 +441,17 @@ public abstract class BaseObjectPoolConfig<T> extends BaseObject implements Clon
}
/**
- * Sets the value for the {@code minEvictableIdleTime} configuration
- * attribute for pools created with this configuration instance.
- *
- * @param minEvictableIdleTime The new setting of
- * {@code minEvictableIdleTime} for this configuration instance
- *
- * @see GenericObjectPool#getMinEvictableIdleTime()
- * @see GenericKeyedObjectPool#getMinEvictableIdleTime()
- * @since 2.10.0
- */
- public void setMinEvictableIdleTime(final Duration minEvictableIdleTime) {
- this.minEvictableIdleTime = minEvictableIdleTime;
- }
-
- /**
- * Sets the value for the {@code minEvictableIdleTime} configuration
+ * Gets the value for the {@code numTestsPerEvictionRun} configuration
* attribute for pools created with this configuration instance.
*
- * @param minEvictableIdleTimeMillis The new setting of
- * {@code minEvictableIdleTime} for this configuration instance
+ * @return The current setting of {@code numTestsPerEvictionRun} for this
+ * configuration instance
*
- * @see GenericObjectPool#getMinEvictableIdleTimeMillis()
- * @see GenericKeyedObjectPool#getMinEvictableIdleTimeMillis()
- * @deprecated Use {@link #setSoftMinEvictableIdleTime(Duration)}.
+ * @see GenericObjectPool#getNumTestsPerEvictionRun()
+ * @see GenericKeyedObjectPool#getNumTestsPerEvictionRun()
*/
- @Deprecated
- public void setMinEvictableIdleTimeMillis(final long minEvictableIdleTimeMillis) {
- this.minEvictableIdleTime = Duration.ofMillis(minEvictableIdleTimeMillis);
+ public int getNumTestsPerEvictionRun() {
+ return numTestsPerEvictionRun;
}
/**
@@ -436,98 +487,135 @@ public abstract class BaseObjectPoolConfig<T> extends BaseObject implements Clon
}
/**
- * Sets the value for the {@code softMinEvictableIdleTime}
- * configuration attribute for pools created with this configuration
- * instance.
+ * Gets the value for the {@code testOnBorrow} configuration attribute for
+ * pools created with this configuration instance.
*
- * @param softMinEvictableIdleTimeMillis The new setting of
- * {@code softMinEvictableIdleTime} for this configuration
- * instance
+ * @return The current setting of {@code testOnBorrow} for this
+ * configuration instance
*
- * @see GenericObjectPool#getSoftMinEvictableIdleTimeMillis()
- * @see GenericKeyedObjectPool#getSoftMinEvictableIdleTimeMillis()
- * @deprecated Use {@link #setSoftMinEvictableIdleTime(Duration)}.
+ * @see GenericObjectPool#getTestOnBorrow()
+ * @see GenericKeyedObjectPool#getTestOnBorrow()
*/
- @Deprecated
- public void setSoftMinEvictableIdleTimeMillis(
- final long softMinEvictableIdleTimeMillis) {
- this.softMinEvictableIdleTime = Duration.ofMillis(softMinEvictableIdleTimeMillis);
+ public boolean getTestOnBorrow() {
+ return testOnBorrow;
}
/**
- * Sets the value for the {@code softMinEvictableIdleTime}
- * configuration attribute for pools created with this configuration
- * instance.
+ * Gets the value for the {@code testOnCreate} configuration attribute for
+ * pools created with this configuration instance.
*
- * @param softMinEvictableIdleTime The new setting of
- * {@code softMinEvictableIdleTime} for this configuration
- * instance
+ * @return The current setting of {@code testOnCreate} for this
+ * configuration instance
*
- * @see GenericObjectPool#getSoftMinEvictableIdleTime()
- * @see GenericKeyedObjectPool#getSoftMinEvictableIdleTime()
- * @since 2.10.0
+ * @see GenericObjectPool#getTestOnCreate()
+ * @see GenericKeyedObjectPool#getTestOnCreate()
+ *
+ * @since 2.2
*/
- public void setSoftMinEvictableIdleTime(final Duration softMinEvictableIdleTime) {
- this.softMinEvictableIdleTime = softMinEvictableIdleTime;
+ public boolean getTestOnCreate() {
+ return testOnCreate;
}
/**
- * Gets the value for the {@code numTestsPerEvictionRun} configuration
- * attribute for pools created with this configuration instance.
+ * Gets the value for the {@code testOnReturn} configuration attribute for
+ * pools created with this configuration instance.
*
- * @return The current setting of {@code numTestsPerEvictionRun} for this
+ * @return The current setting of {@code testOnReturn} for this
* configuration instance
*
- * @see GenericObjectPool#getNumTestsPerEvictionRun()
- * @see GenericKeyedObjectPool#getNumTestsPerEvictionRun()
+ * @see GenericObjectPool#getTestOnReturn()
+ * @see GenericKeyedObjectPool#getTestOnReturn()
*/
- public int getNumTestsPerEvictionRun() {
- return numTestsPerEvictionRun;
+ public boolean getTestOnReturn() {
+ return testOnReturn;
}
/**
- * Sets the value for the {@code numTestsPerEvictionRun} configuration
- * attribute for pools created with this configuration instance.
+ * Gets the value for the {@code testWhileIdle} configuration attribute for
+ * pools created with this configuration instance.
*
- * @param numTestsPerEvictionRun The new setting of
- * {@code numTestsPerEvictionRun} for this configuration instance
+ * @return The current setting of {@code testWhileIdle} for this
+ * configuration instance
*
- * @see GenericObjectPool#getNumTestsPerEvictionRun()
- * @see GenericKeyedObjectPool#getNumTestsPerEvictionRun()
+ * @see GenericObjectPool#getTestWhileIdle()
+ * @see GenericKeyedObjectPool#getTestWhileIdle()
*/
- public void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) {
- this.numTestsPerEvictionRun = numTestsPerEvictionRun;
+ public boolean getTestWhileIdle() {
+ return testWhileIdle;
}
/**
- * Gets the value for the {@code evictorShutdownTimeout} configuration
+ * Gets the value for the {@code timeBetweenEvictionRuns} configuration
* attribute for pools created with this configuration instance.
*
- * @return The current setting of {@code evictorShutdownTimeout} for
+ * @return The current setting of {@code timeBetweenEvictionRuns} for
* this configuration instance
*
- * @see GenericObjectPool#getEvictorShutdownTimeoutMillis()
- * @see GenericKeyedObjectPool#getEvictorShutdownTimeoutMillis()
- * @deprecated Use {@link #getEvictorShutdownTimeout()}.
+ * @see GenericObjectPool#getTimeBetweenEvictionRuns()
+ * @see GenericKeyedObjectPool#getTimeBetweenEvictionRuns()
+ * @since 2.10.0
*/
- @Deprecated
- public long getEvictorShutdownTimeoutMillis() {
- return evictorShutdownTimeout.toMillis();
+ public Duration getTimeBetweenEvictionRuns() {
+ return timeBetweenEvictionRuns;
}
/**
- * Gets the value for the {@code evictorShutdownTimeout} configuration
+ * Gets the value for the {@code timeBetweenEvictionRuns} configuration
* attribute for pools created with this configuration instance.
*
- * @return The current setting of {@code evictorShutdownTimeout} for
+ * @return The current setting of {@code timeBetweenEvictionRuns} for
* this configuration instance
*
- * @see GenericObjectPool#getEvictorShutdownTimeout()
- * @see GenericKeyedObjectPool#getEvictorShutdownTimeout()
- * @since 2.10.0
+ * @see GenericObjectPool#getTimeBetweenEvictionRunsMillis()
+ * @see GenericKeyedObjectPool#getTimeBetweenEvictionRunsMillis()
+ * @deprecated Use {@link #getTimeBetweenEvictionRuns()}.
*/
- public Duration getEvictorShutdownTimeout() {
- return evictorShutdownTimeout;
+ @Deprecated
+ public long getTimeBetweenEvictionRunsMillis() {
+ return timeBetweenEvictionRuns.toMillis();
+ }
+
+ /**
+ * Sets the value for the {@code blockWhenExhausted} configuration attribute
+ * for pools created with this configuration instance.
+ *
+ * @param blockWhenExhausted The new setting of {@code blockWhenExhausted}
+ * for this configuration instance
+ *
+ * @see GenericObjectPool#getBlockWhenExhausted()
+ * @see GenericKeyedObjectPool#getBlockWhenExhausted()
+ */
+ public void setBlockWhenExhausted(final boolean blockWhenExhausted) {
+ this.blockWhenExhausted = blockWhenExhausted;
+ }
+
+ /**
+ * Sets the value for the {@code evictionPolicyClass} configuration
+ * attribute for pools created with this configuration instance.
+ *
+ * @param evictionPolicy The new setting of
+ * {@code evictionPolicyClass} for this configuration instance
+ *
+ * @see GenericObjectPool#getEvictionPolicy()
+ * @see GenericKeyedObjectPool#getEvictionPolicy()
+ * @since 2.6.0
+ */
+ public void setEvictionPolicy(final EvictionPolicy<T> evictionPolicy) {
+ this.evictionPolicy = evictionPolicy;
+ }
+
+ /**
+ * Sets the value for the {@code evictionPolicyClassName} configuration
+ * attribute for pools created with this configuration instance.
+ *
+ * @param evictionPolicyClassName The new setting of
+ * {@code evictionPolicyClassName} for this configuration instance
+ *
+ * @see GenericObjectPool#getEvictionPolicyClassName()
+ * @see GenericKeyedObjectPool#getEvictionPolicyClassName()
+ */
+ public void setEvictionPolicyClassName(final String evictionPolicyClassName) {
+ this.evictionPolicyClassName = evictionPolicyClassName;
}
/**
@@ -564,341 +652,253 @@ public abstract class BaseObjectPoolConfig<T> extends BaseObject implements Clon
}
/**
- * Gets the value for the {@code testOnCreate} configuration attribute for
- * pools created with this configuration instance.
- *
- * @return The current setting of {@code testOnCreate} for this
- * configuration instance
- *
- * @see GenericObjectPool#getTestOnCreate()
- * @see GenericKeyedObjectPool#getTestOnCreate()
- *
- * @since 2.2
- */
- public boolean getTestOnCreate() {
- return testOnCreate;
- }
-
- /**
- * Sets the value for the {@code testOnCreate} configuration attribute for
- * pools created with this configuration instance.
+ * Sets the value for the {@code fairness} configuration attribute for pools
+ * created with this configuration instance.
*
- * @param testOnCreate The new setting of {@code testOnCreate}
+ * @param fairness The new setting of {@code fairness}
* for this configuration instance
*
- * @see GenericObjectPool#getTestOnCreate()
- * @see GenericKeyedObjectPool#getTestOnCreate()
- *
- * @since 2.2
- */
- public void setTestOnCreate(final boolean testOnCreate) {
- this.testOnCreate = testOnCreate;
- }
-
- /**
- * Gets the value for the {@code testOnBorrow} configuration attribute for
- * pools created with this configuration instance.
- *
- * @return The current setting of {@code testOnBorrow} for this
- * configuration instance
- *
- * @see GenericObjectPool#getTestOnBorrow()
- * @see GenericKeyedObjectPool#getTestOnBorrow()
+ * @see GenericObjectPool#getFairness()
+ * @see GenericKeyedObjectPool#getFairness()
*/
- public boolean getTestOnBorrow() {
- return testOnBorrow;
+ public void setFairness(final boolean fairness) {
+ this.fairness = fairness;
}
/**
- * Sets the value for the {@code testOnBorrow} configuration attribute for
+ * Sets the value of the flag that determines if JMX will be enabled for
* pools created with this configuration instance.
*
- * @param testOnBorrow The new setting of {@code testOnBorrow}
+ * @param jmxEnabled The new setting of {@code jmxEnabled}
* for this configuration instance
- *
- * @see GenericObjectPool#getTestOnBorrow()
- * @see GenericKeyedObjectPool#getTestOnBorrow()
*/
- public void setTestOnBorrow(final boolean testOnBorrow) {
- this.testOnBorrow = testOnBorrow;
+ public void setJmxEnabled(final boolean jmxEnabled) {
+ this.jmxEnabled = jmxEnabled;
}
/**
- * Gets the value for the {@code testOnReturn} configuration attribute for
- * pools created with this configuration instance.
- *
- * @return The current setting of {@code testOnReturn} for this
- * configuration instance
+ * Sets the value of the JMX name base that will be used as part of the
+ * name assigned to JMX enabled pools created with this configuration
+ * instance. A value of {@code null} means that the pool will define
+ * the JMX name base.
*
- * @see GenericObjectPool#getTestOnReturn()
- * @see GenericKeyedObjectPool#getTestOnReturn()
+ * @param jmxNameBase The new setting of {@code jmxNameBase}
+ * for this configuration instance
*/
- public boolean getTestOnReturn() {
- return testOnReturn;
+ public void setJmxNameBase(final String jmxNameBase) {
+ this.jmxNameBase = jmxNameBase;
}
/**
- * Sets the value for the {@code testOnReturn} configuration attribute for
- * pools created with this configuration instance.
+ * Sets the value of the JMX name prefix that will be used as part of the
+ * name assigned to JMX enabled pools created with this configuration
+ * instance.
*
- * @param testOnReturn The new setting of {@code testOnReturn}
+ * @param jmxNamePrefix The new setting of {@code jmxNamePrefix}
* for this configuration instance
- *
- * @see GenericObjectPool#getTestOnReturn()
- * @see GenericKeyedObjectPool#getTestOnReturn()
*/
- public void setTestOnReturn(final boolean testOnReturn) {
- this.testOnReturn = testOnReturn;
+ public void setJmxNamePrefix(final String jmxNamePrefix) {
+ this.jmxNamePrefix = jmxNamePrefix;
}
/**
- * Gets the value for the {@code testWhileIdle} configuration attribute for
- * pools created with this configuration instance.
+ * Sets the value for the {@code lifo} configuration attribute for pools
+ * created with this configuration instance.
*
- * @return The current setting of {@code testWhileIdle} for this
- * configuration instance
+ * @param lifo The new setting of {@code lifo}
+ * for this configuration instance
*
- * @see GenericObjectPool#getTestWhileIdle()
- * @see GenericKeyedObjectPool#getTestWhileIdle()
+ * @see GenericObjectPool#getLifo()
+ * @see GenericKeyedObjectPool#getLifo()
*/
- public boolean getTestWhileIdle() {
- return testWhileIdle;
+ public void setLifo(final boolean lifo) {
+ this.lifo = lifo;
}
/**
- * Sets the value for the {@code testWhileIdle} configuration attribute for
- * pools created with this configuration instance.
+ * Sets the value for the {@code maxWait} configuration attribute for pools
+ * created with this configuration instance.
*
- * @param testWhileIdle The new setting of {@code testWhileIdle}
+ * @param maxWaitMillis The new setting of {@code maxWaitMillis}
* for this configuration instance
*
- * @see GenericObjectPool#getTestWhileIdle()
- * @see GenericKeyedObjectPool#getTestWhileIdle()
+ * @see GenericObjectPool#getMaxWaitMillis()
+ * @see GenericKeyedObjectPool#getMaxWaitMillis()
*/
- public void setTestWhileIdle(final boolean testWhileIdle) {
- this.testWhileIdle = testWhileIdle;
+ public void setMaxWaitMillis(final long maxWaitMillis) {
+ this.maxWaitMillis = Duration.ofMillis(maxWaitMillis);
}
/**
- * Gets the value for the {@code timeBetweenEvictionRuns} configuration
+ * Sets the value for the {@code minEvictableIdleTime} configuration
* attribute for pools created with this configuration instance.
*
- * @return The current setting of {@code timeBetweenEvictionRuns} for
- * this configuration instance
+ * @param minEvictableIdleTime The new setting of
+ * {@code minEvictableIdleTime} for this configuration instance
*
- * @see GenericObjectPool#getTimeBetweenEvictionRuns()
- * @see GenericKeyedObjectPool#getTimeBetweenEvictionRuns()
+ * @see GenericObjectPool#getMinEvictableIdleTime()
+ * @see GenericKeyedObjectPool#getMinEvictableIdleTime()
* @since 2.10.0
*/
- public Duration getTimeBetweenEvictionRuns() {
- return timeBetweenEvictionRuns;
+ public void setMinEvictableIdleTime(final Duration minEvictableIdleTime) {
+ this.minEvictableIdleTime = minEvictableIdleTime;
}
/**
- * Gets the value for the {@code timeBetweenEvictionRuns} configuration
+ * Sets the value for the {@code minEvictableIdleTime} configuration
* attribute for pools created with this configuration instance.
*
- * @return The current setting of {@code timeBetweenEvictionRuns} for
- * this configuration instance
+ * @param minEvictableIdleTimeMillis The new setting of
+ * {@code minEvictableIdleTime} for this configuration instance
*
- * @see GenericObjectPool#getTimeBetweenEvictionRunsMillis()
- * @see GenericKeyedObjectPool#getTimeBetweenEvictionRunsMillis()
- * @deprecated Use {@link #getTimeBetweenEvictionRuns()}.
+ * @see GenericObjectPool#getMinEvictableIdleTimeMillis()
+ * @see GenericKeyedObjectPool#getMinEvictableIdleTimeMillis()
+ * @deprecated Use {@link #setSoftMinEvictableIdleTime(Duration)}.
*/
@Deprecated
- public long getTimeBetweenEvictionRunsMillis() {
- return timeBetweenEvictionRuns.toMillis();
+ public void setMinEvictableIdleTimeMillis(final long minEvictableIdleTimeMillis) {
+ this.minEvictableIdleTime = Duration.ofMillis(minEvictableIdleTimeMillis);
}
/**
- * Sets the value for the {@code timeBetweenEvictionRuns} configuration
+ * Sets the value for the {@code numTestsPerEvictionRun} configuration
* attribute for pools created with this configuration instance.
*
- * @param timeBetweenEvictionRunsMillis The new setting of
- * {@code timeBetweenEvictionRuns} for this configuration
- * instance
+ * @param numTestsPerEvictionRun The new setting of
+ * {@code numTestsPerEvictionRun} for this configuration instance
*
- * @see GenericObjectPool#getTimeBetweenEvictionRuns()
- * @see GenericKeyedObjectPool#getTimeBetweenEvictionRuns()
- * @since 2.10.0
+ * @see GenericObjectPool#getNumTestsPerEvictionRun()
+ * @see GenericKeyedObjectPool#getNumTestsPerEvictionRun()
*/
- public void setTimeBetweenEvictionRuns(final Duration timeBetweenEvictionRunsMillis) {
- this.timeBetweenEvictionRuns = timeBetweenEvictionRunsMillis;
+ public void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) {
+ this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
- * Sets the value for the {@code timeBetweenEvictionRuns} configuration
- * attribute for pools created with this configuration instance.
+ * Sets the value for the {@code softMinEvictableIdleTime}
+ * configuration attribute for pools created with this configuration
+ * instance.
*
- * @param timeBetweenEvictionRunsMillis The new setting of
- * {@code timeBetweenEvictionRuns} for this configuration
+ * @param softMinEvictableIdleTime The new setting of
+ * {@code softMinEvictableIdleTime} for this configuration
* instance
*
- * @see GenericObjectPool#getTimeBetweenEvictionRunsMillis()
- * @see GenericKeyedObjectPool#getTimeBetweenEvictionRunsMillis()
- * @deprecated Use {@link #setTimeBetweenEvictionRuns(Duration)}.
- */
- @Deprecated
- public void setTimeBetweenEvictionRunsMillis(final long timeBetweenEvictionRunsMillis) {
- this.timeBetweenEvictionRuns = Duration.ofMillis(timeBetweenEvictionRunsMillis);
- }
-
- /**
- * Gets the value for the {@code evictionPolicyClass} configuration
- * attribute for pools created with this configuration instance.
- *
- * @return The current setting of {@code evictionPolicyClass} for this
- * configuration instance
- *
- * @see GenericObjectPool#getEvictionPolicy()
- * @see GenericKeyedObjectPool#getEvictionPolicy()
- * @since 2.6.0
+ * @see GenericObjectPool#getSoftMinEvictableIdleTime()
+ * @see GenericKeyedObjectPool#getSoftMinEvictableIdleTime()
+ * @since 2.10.0
*/
- public EvictionPolicy<T> getEvictionPolicy() {
- return evictionPolicy;
+ public void setSoftMinEvictableIdleTime(final Duration softMinEvictableIdleTime) {
+ this.softMinEvictableIdleTime = softMinEvictableIdleTime;
}
/**
- * Gets the value for the {@code evictionPolicyClassName} configuration
- * attribute for pools created with this configuration instance.
+ * Sets the value for the {@code softMinEvictableIdleTime}
+ * configuration attribute for pools created with this configuration
+ * instance.
*
- * @return The current setting of {@code evictionPolicyClassName} for this
- * configuration instance
+ * @param softMinEvictableIdleTimeMillis The new setting of
+ * {@code softMinEvictableIdleTime} for this configuration
+ * instance
*
- * @see GenericObjectPool#getEvictionPolicyClassName()
- * @see GenericKeyedObjectPool#getEvictionPolicyClassName()
+ * @see GenericObjectPool#getSoftMinEvictableIdleTimeMillis()
+ * @see GenericKeyedObjectPool#getSoftMinEvictableIdleTimeMillis()
+ * @deprecated Use {@link #setSoftMinEvictableIdleTime(Duration)}.
*/
- public String getEvictionPolicyClassName() {
- return evictionPolicyClassName;
+ @Deprecated
+ public void setSoftMinEvictableIdleTimeMillis(
+ final long softMinEvictableIdleTimeMillis) {
+ this.softMinEvictableIdleTime = Duration.ofMillis(softMinEvictableIdleTimeMillis);
}
/**
- * Sets the value for the {@code evictionPolicyClass} configuration
- * attribute for pools created with this configuration instance.
+ * Sets the value for the {@code testOnBorrow} configuration attribute for
+ * pools created with this configuration instance.
*
- * @param evictionPolicy The new setting of
- * {@code evictionPolicyClass} for this configuration instance
+ * @param testOnBorrow The new setting of {@code testOnBorrow}
+ * for this configuration instance
*
- * @see GenericObjectPool#getEvictionPolicy()
- * @see GenericKeyedObjectPool#getEvictionPolicy()
- * @since 2.6.0
+ * @see GenericObjectPool#getTestOnBorrow()
+ * @see GenericKeyedObjectPool#getTestOnBorrow()
*/
- public void setEvictionPolicy(final EvictionPolicy<T> evictionPolicy) {
- this.evictionPolicy = evictionPolicy;
+ public void setTestOnBorrow(final boolean testOnBorrow) {
+ this.testOnBorrow = testOnBorrow;
}
/**
- * Sets the value for the {@code evictionPolicyClassName} configuration
- * attribute for pools created with this configuration instance.
- *
- * @param evictionPolicyClassName The new setting of
- * {@code evictionPolicyClassName} for this configuration instance
+ * Sets the value for the {@code testOnCreate} configuration attribute for
+ * pools created with this configuration instance.
*
- * @see GenericObjectPool#getEvictionPolicyClassName()
- * @see GenericKeyedObjectPool#getEvictionPolicyClassName()
- */
- public void setEvictionPolicyClassName(final String evictionPolicyClassName) {
- this.evictionPolicyClassName = evictionPolicyClassName;
- }
-
- /**
- * Gets the value for the {@code blockWhenExhausted} configuration attribute
- * for pools created with this configuration instance.
+ * @param testOnCreate The new setting of {@code testOnCreate}
+ * for this configuration instance
*
- * @return The current setting of {@code blockWhenExhausted} for this
- * configuration instance
+ * @see GenericObjectPool#getTestOnCreate()
+ * @see GenericKeyedObjectPool#getTestOnCreate()
*
- * @see GenericObjectPool#getBlockWhenExhausted()
- * @see GenericKeyedObjectPool#getBlockWhenExhausted()
+ * @since 2.2
*/
- public boolean getBlockWhenExhausted() {
- return blockWhenExhausted;
+ public void setTestOnCreate(final boolean testOnCreate) {
+ this.testOnCreate = testOnCreate;
}
/**
- * Sets the value for the {@code blockWhenExhausted} configuration attribute
- * for pools created with this configuration instance.
+ * Sets the value for the {@code testOnReturn} configuration attribute for
+ * pools created with this configuration instance.
*
- * @param blockWhenExhausted The new setting of {@code blockWhenExhausted}
+ * @param testOnReturn The new setting of {@code testOnReturn}
* for this configuration instance
*
- * @see GenericObjectPool#getBlockWhenExhausted()
- * @see GenericKeyedObjectPool#getBlockWhenExhausted()
- */
- public void setBlockWhenExhausted(final boolean blockWhenExhausted) {
- this.blockWhenExhausted = blockWhenExhausted;
- }
-
- /**
- * Gets the value of the flag that determines if JMX will be enabled for
- * pools created with this configuration instance.
- *
- * @return The current setting of {@code jmxEnabled} for this configuration
- * instance
+ * @see GenericObjectPool#getTestOnReturn()
+ * @see GenericKeyedObjectPool#getTestOnReturn()
*/
- public boolean getJmxEnabled() {
- return jmxEnabled;
+ public void setTestOnReturn(final boolean testOnReturn) {
+ this.testOnReturn = testOnReturn;
}
/**
- * Sets the value of the flag that determines if JMX will be enabled for
+ * Sets the value for the {@code testWhileIdle} configuration attribute for
* pools created with this configuration instance.
*
- * @param jmxEnabled The new setting of {@code jmxEnabled}
+ * @param testWhileIdle The new setting of {@code testWhileIdle}
* for this configuration instance
- */
- public void setJmxEnabled(final boolean jmxEnabled) {
- this.jmxEnabled = jmxEnabled;
- }
-
- /**
- * Gets the value of the JMX name base that will be used as part of the
- * name assigned to JMX enabled pools created with this configuration
- * instance. A value of {@code null} means that the pool will define
- * the JMX name base.
*
- * @return The current setting of {@code jmxNameBase} for this
- * configuration instance
+ * @see GenericObjectPool#getTestWhileIdle()
+ * @see GenericKeyedObjectPool#getTestWhileIdle()
*/
- public String getJmxNameBase() {
- return jmxNameBase;
+ public void setTestWhileIdle(final boolean testWhileIdle) {
+ this.testWhileIdle = testWhileIdle;
}
/**
- * Sets the value of the JMX name base that will be used as part of the
- * name assigned to JMX enabled pools created with this configuration
- * instance. A value of {@code null} means that the pool will define
- * the JMX name base.
+ * Sets the value for the {@code timeBetweenEvictionRuns} configuration
+ * attribute for pools created with this configuration instance.
*
- * @param jmxNameBase The new setting of {@code jmxNameBase}
- * for this configuration instance
- */
- public void setJmxNameBase(final String jmxNameBase) {
- this.jmxNameBase = jmxNameBase;
- }
-
- /**
- * Gets the value of the JMX name prefix that will be used as part of the
- * name assigned to JMX enabled pools created with this configuration
- * instance.
+ * @param timeBetweenEvictionRunsMillis The new setting of
+ * {@code timeBetweenEvictionRuns} for this configuration
+ * instance
*
- * @return The current setting of {@code jmxNamePrefix} for this
- * configuration instance
+ * @see GenericObjectPool#getTimeBetweenEvictionRuns()
+ * @see GenericKeyedObjectPool#getTimeBetweenEvictionRuns()
+ * @since 2.10.0
*/
- public String getJmxNamePrefix() {
- return jmxNamePrefix;
+ public void setTimeBetweenEvictionRuns(final Duration timeBetweenEvictionRunsMillis) {
+ this.timeBetweenEvictionRuns = timeBetweenEvictionRunsMillis;
}
/**
- * Sets the value of the JMX name prefix that will be used as part of the
- * name assigned to JMX enabled pools created with this configuration
- * instance.
+ * Sets the value for the {@code timeBetweenEvictionRuns} configuration
+ * attribute for pools created with this configuration instance.
*
- * @param jmxNamePrefix The new setting of {@code jmxNamePrefix}
- * for this configuration instance
+ * @param timeBetweenEvictionRunsMillis The new setting of
+ * {@code timeBetweenEvictionRuns} for this configuration
+ * instance
+ *
+ * @see GenericObjectPool#getTimeBetweenEvictionRunsMillis()
+ * @see GenericKeyedObjectPool#getTimeBetweenEvictionRunsMillis()
+ * @deprecated Use {@link #setTimeBetweenEvictionRuns(Duration)}.
*/
- public void setJmxNamePrefix(final String jmxNamePrefix) {
- this.jmxNamePrefix = jmxNamePrefix;
+ @Deprecated
+ public void setTimeBetweenEvictionRunsMillis(final long timeBetweenEvictionRunsMillis) {
+ this.timeBetweenEvictionRuns = Duration.ofMillis(timeBetweenEvictionRunsMillis);
}
@Override
diff --git a/src/main/java/org/apache/commons/pool2/impl/CallStack.java b/src/main/java/org/apache/commons/pool2/impl/CallStack.java
index da7d4bb..a6b58c6 100644
--- a/src/main/java/org/apache/commons/pool2/impl/CallStack.java
+++ b/src/main/java/org/apache/commons/pool2/impl/CallStack.java
@@ -32,13 +32,10 @@ import java.io.PrintWriter;
public interface CallStack {
/**
- * Prints the current stack trace if available to a PrintWriter. The format is undefined and is primarily useful
- * for debugging issues with {@link PooledObject} usage in user code.
- *
- * @param writer a PrintWriter to write the current stack trace to if available
- * @return true if a stack trace was available to print or false if nothing was printed
+ * Clears the current stack trace snapshot. Subsequent calls to {@link #printStackTrace(PrintWriter)} will be
+ * no-ops until another call to {@link #fillInStackTrace()}.
*/
- boolean printStackTrace(final PrintWriter writer);
+ void clear();
/**
* Takes a snapshot of the current call stack. Subsequent calls to {@link #printStackTrace(PrintWriter)} will print
@@ -47,8 +44,11 @@ public interface CallStack {
void fillInStackTrace();
/**
- * Clears the current stack trace snapshot. Subsequent calls to {@link #printStackTrace(PrintWriter)} will be
- * no-ops until another call to {@link #fillInStackTrace()}.
+ * Prints the current stack trace if available to a PrintWriter. The format is undefined and is primarily useful
+ * for debugging issues with {@link PooledObject} usage in user code.
+ *
+ * @param writer a PrintWriter to write the current stack trace to if available
+ * @return true if a stack trace was available to print or false if nothing was printed
*/
- void clear();
+ boolean printStackTrace(final PrintWriter writer);
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObject.java b/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObject.java
index 7d513e1..422ab74 100644
--- a/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObject.java
+++ b/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObject.java
@@ -57,72 +57,29 @@ public class DefaultPooledObject<T> implements PooledObject<T> {
this.object = object;
}
- @Override
- public T getObject() {
- return object;
- }
-
- @Override
- public long getCreateTime() {
- return createTimeMillis;
- }
-
- @Override
- public long getActiveTimeMillis() {
- // Take copies to avoid threading issues
- final long rTime = lastReturnTimeMillis;
- final long bTime = lastBorrowTimeMillis;
-
- if (rTime > bTime) {
- return rTime - bTime;
- }
- return System.currentTimeMillis() - bTime;
- }
-
- @Override
- public long getIdleTimeMillis() {
- final long elapsed = System.currentTimeMillis() - lastReturnTimeMillis;
- // elapsed may be negative if:
- // - another thread updates lastReturnTime during the calculation window
- // - System.currentTimeMillis() is not monotonic (e.g. system time is set back)
- return elapsed >= 0 ? elapsed : 0;
- }
-
- @Override
- public long getLastBorrowTime() {
- return lastBorrowTimeMillis;
- }
-
- @Override
- public long getLastReturnTime() {
- return lastReturnTimeMillis;
- }
-
/**
- * Gets the number of times this object has been borrowed.
- * @return The number of times this object has been borrowed.
- * @since 2.1
- */
- @Override
- public long getBorrowedCount() {
- return borrowedCount;
- }
-
- /**
- * Gets an estimate of the last time this object was used. If the class
- * of the pooled object implements {@link TrackedUse}, what is returned is
- * the maximum of {@link TrackedUse#getLastUsed()} and
- * {@link #getLastBorrowTime()}; otherwise this method gives the same
- * value as {@link #getLastBorrowTime()}.
+ * Allocates the object.
*
- * @return the last time this object was used
+ * @return {@code true} if the original state was {@link PooledObjectState#IDLE IDLE}
*/
@Override
- public long getLastUsedTime() {
- if (object instanceof TrackedUse) {
- return Math.max(((TrackedUse) object).getLastUsed(), lastUseTimeMillis);
+ public synchronized boolean allocate() {
+ if (state == PooledObjectState.IDLE) {
+ state = PooledObjectState.ALLOCATED;
+ lastBorrowTimeMillis = System.currentTimeMillis();
+ lastUseTimeMillis = lastBorrowTimeMillis;
+ borrowedCount++;
+ if (logAbandoned) {
+ borrowedBy.fillInStackTrace();
+ }
+ return true;
+ } else if (state == PooledObjectState.EVICTION) {
+ // TODO Allocate anyway and ignore eviction test
+ state = PooledObjectState.EVICTION_RETURN_TO_HEAD;
}
- return lastUseTimeMillis;
+ // TODO if validating and testOnBorrow == true then pre-allocate for
+ // performance
+ return false;
}
@Override
@@ -139,23 +96,21 @@ public class DefaultPooledObject<T> implements PooledObject<T> {
return (int)Math.min(Math.max(lastActiveDiff, Integer.MIN_VALUE), Integer.MAX_VALUE);
}
+ /**
+ * Deallocates the object and sets it {@link PooledObjectState#IDLE IDLE}
+ * if it is currently {@link PooledObjectState#ALLOCATED ALLOCATED}
+ * or {@link PooledObjectState#RETURNING RETURNING}.
+ *
+ * @return {@code true} if the state was {@link PooledObjectState#ALLOCATED ALLOCATED}
+ * or {@link PooledObjectState#RETURNING RETURNING}.
+ */
@Override
- public String toString() {
- final StringBuilder result = new StringBuilder();
- result.append("Object: ");
- result.append(object.toString());
- result.append(", State: ");
- synchronized (this) {
- result.append(state.toString());
- }
- return result.toString();
- // TODO add other attributes
- }
-
- @Override
- public synchronized boolean startEvictionTest() {
- if (state == PooledObjectState.IDLE) {
- state = PooledObjectState.EVICTION;
+ public synchronized boolean deallocate() {
+ if (state == PooledObjectState.ALLOCATED ||
+ state == PooledObjectState.RETURNING) {
+ state = PooledObjectState.IDLE;
+ lastReturnTimeMillis = System.currentTimeMillis();
+ borrowedBy.clear();
return true;
}
@@ -178,73 +133,72 @@ public class DefaultPooledObject<T> implements PooledObject<T> {
return false;
}
- /**
- * Allocates the object.
- *
- * @return {@code true} if the original state was {@link PooledObjectState#IDLE IDLE}
- */
@Override
- public synchronized boolean allocate() {
- if (state == PooledObjectState.IDLE) {
- state = PooledObjectState.ALLOCATED;
- lastBorrowTimeMillis = System.currentTimeMillis();
- lastUseTimeMillis = lastBorrowTimeMillis;
- borrowedCount++;
- if (logAbandoned) {
- borrowedBy.fillInStackTrace();
- }
- return true;
- } else if (state == PooledObjectState.EVICTION) {
- // TODO Allocate anyway and ignore eviction test
- state = PooledObjectState.EVICTION_RETURN_TO_HEAD;
+ public long getActiveTimeMillis() {
+ // Take copies to avoid threading issues
+ final long rTime = lastReturnTimeMillis;
+ final long bTime = lastBorrowTimeMillis;
+
+ if (rTime > bTime) {
+ return rTime - bTime;
}
- // TODO if validating and testOnBorrow == true then pre-allocate for
- // performance
- return false;
+ return System.currentTimeMillis() - bTime;
}
/**
- * Deallocates the object and sets it {@link PooledObjectState#IDLE IDLE}
- * if it is currently {@link PooledObjectState#ALLOCATED ALLOCATED}
- * or {@link PooledObjectState#RETURNING RETURNING}.
- *
- * @return {@code true} if the state was {@link PooledObjectState#ALLOCATED ALLOCATED}
- * or {@link PooledObjectState#RETURNING RETURNING}.
+ * Gets the number of times this object has been borrowed.
+ * @return The number of times this object has been borrowed.
+ * @since 2.1
*/
@Override
- public synchronized boolean deallocate() {
- if (state == PooledObjectState.ALLOCATED ||
- state == PooledObjectState.RETURNING) {
- state = PooledObjectState.IDLE;
- lastReturnTimeMillis = System.currentTimeMillis();
- borrowedBy.clear();
- return true;
- }
+ public long getBorrowedCount() {
+ return borrowedCount;
+ }
- return false;
+ @Override
+ public long getCreateTime() {
+ return createTimeMillis;
}
- /**
- * Sets the state to {@link PooledObjectState#INVALID INVALID}
- */
@Override
- public synchronized void invalidate() {
- state = PooledObjectState.INVALID;
+ public long getIdleTimeMillis() {
+ final long elapsed = System.currentTimeMillis() - lastReturnTimeMillis;
+ // elapsed may be negative if:
+ // - another thread updates lastReturnTime during the calculation window
+ // - System.currentTimeMillis() is not monotonic (e.g. system time is set back)
+ return elapsed >= 0 ? elapsed : 0;
}
@Override
- public void use() {
- lastUseTimeMillis = System.currentTimeMillis();
- usedBy.fillInStackTrace();
+ public long getLastBorrowTime() {
+ return lastBorrowTimeMillis;
}
@Override
- public void printStackTrace(final PrintWriter writer) {
- boolean written = borrowedBy.printStackTrace(writer);
- written |= usedBy.printStackTrace(writer);
- if (written) {
- writer.flush();
+ public long getLastReturnTime() {
+ return lastReturnTimeMillis;
+ }
+
+ /**
+ * Gets an estimate of the last time this object was used. If the class
+ * of the pooled object implements {@link TrackedUse}, what is returned is
+ * the maximum of {@link TrackedUse#getLastUsed()} and
+ * {@link #getLastBorrowTime()}; otherwise this method gives the same
+ * value as {@link #getLastBorrowTime()}.
+ *
+ * @return the last time this object was used
+ */
+ @Override
+ public long getLastUsedTime() {
+ if (object instanceof TrackedUse) {
+ return Math.max(((TrackedUse) object).getLastUsed(), lastUseTimeMillis);
}
+ return lastUseTimeMillis;
+ }
+
+ @Override
+ public T getObject() {
+ return object;
}
/**
@@ -257,6 +211,14 @@ public class DefaultPooledObject<T> implements PooledObject<T> {
}
/**
+ * Sets the state to {@link PooledObjectState#INVALID INVALID}
+ */
+ @Override
+ public synchronized void invalidate() {
+ state = PooledObjectState.INVALID;
+ }
+
+ /**
* Marks the pooled object as abandoned.
*/
@Override
@@ -273,6 +235,15 @@ public class DefaultPooledObject<T> implements PooledObject<T> {
}
@Override
+ public void printStackTrace(final PrintWriter writer) {
+ boolean written = borrowedBy.printStackTrace(writer);
+ written |= usedBy.printStackTrace(writer);
+ if (written) {
+ writer.flush();
+ }
+ }
+
+ @Override
public void setLogAbandoned(final boolean logAbandoned) {
this.logAbandoned = logAbandoned;
}
@@ -296,4 +267,33 @@ public class DefaultPooledObject<T> implements PooledObject<T> {
false, requireFullStackTrace);
}
+ @Override
+ public synchronized boolean startEvictionTest() {
+ if (state == PooledObjectState.IDLE) {
+ state = PooledObjectState.EVICTION;
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder result = new StringBuilder();
+ result.append("Object: ");
+ result.append(object.toString());
+ result.append(", State: ");
+ synchronized (this) {
+ result.append(state.toString());
+ }
+ return result.toString();
+ // TODO add other attributes
+ }
+
+ @Override
+ public void use() {
+ lastUseTimeMillis = System.currentTimeMillis();
+ usedBy.fillInStackTrace();
+ }
+
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java b/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java
index aacd8a9..a0e1e36 100644
--- a/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java
+++ b/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java
@@ -42,6 +42,11 @@ public class DefaultPooledObjectInfo implements DefaultPooledObjectInfoMBean {
}
@Override
+ public long getBorrowedCount() {
+ return pooledObject.getBorrowedCount();
+ }
+
+ @Override
public long getCreateTime() {
return pooledObject.getCreateTime();
}
@@ -82,18 +87,13 @@ public class DefaultPooledObjectInfo implements DefaultPooledObjectInfoMBean {
}
@Override
- public String getPooledObjectType() {
- return pooledObject.getObject().getClass().getName();
- }
-
- @Override
public String getPooledObjectToString() {
return pooledObject.getObject().toString();
}
@Override
- public long getBorrowedCount() {
- return pooledObject.getBorrowedCount();
+ public String getPooledObjectType() {
+ return pooledObject.getObject().getClass().getName();
}
/**
diff --git a/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java b/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java
index 5e8b3a5..393ae73 100644
--- a/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java
+++ b/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java
@@ -31,6 +31,13 @@ package org.apache.commons.pool2.impl;
*/
public interface DefaultPooledObjectInfoMBean {
/**
+ * Get the number of times this object has been borrowed.
+ * @return The number of times this object has been borrowed.
+ * @since 2.1
+ */
+ long getBorrowedCount();
+
+ /**
* Obtain the time (using the same basis as
* {@link System#currentTimeMillis()}) that pooled object was created.
*
@@ -62,6 +69,7 @@ public interface DefaultPooledObjectInfoMBean {
*/
String getLastBorrowTimeFormatted();
+
/**
* Obtain the stack trace recorded when the pooled object was last borrowed.
*
@@ -70,7 +78,6 @@ public interface DefaultPooledObjectInfoMBean {
*/
String getLastBorrowTrace();
-
/**
* Obtain the time (using the same basis as
* {@link System#currentTimeMillis()})the wrapped object was last returned.
@@ -88,15 +95,6 @@ public interface DefaultPooledObjectInfoMBean {
String getLastReturnTimeFormatted();
/**
- * Obtain the name of the class of the pooled object.
- *
- * @return The pooled object's class name
- *
- * @see Class#getName()
- */
- String getPooledObjectType();
-
- /**
* Provides a String form of the wrapper for debug purposes. The format is
* not fixed and may change at any time.
*
@@ -107,9 +105,11 @@ public interface DefaultPooledObjectInfoMBean {
String getPooledObjectToString();
/**
- * Get the number of times this object has been borrowed.
- * @return The number of times this object has been borrowed.
- * @since 2.1
+ * Obtain the name of the class of the pooled object.
+ *
+ * @return The pooled object's class name
+ *
+ * @see Class#getName()
*/
- long getBorrowedCount();
+ String getPooledObjectType();
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/EvictionTimer.java b/src/main/java/org/apache/commons/pool2/impl/EvictionTimer.java
index a12da3b..e999815 100644
--- a/src/main/java/org/apache/commons/pool2/impl/EvictionTimer.java
+++ b/src/main/java/org/apache/commons/pool2/impl/EvictionTimer.java
@@ -48,105 +48,6 @@ import java.util.concurrent.TimeUnit;
*/
class EvictionTimer {
- /** Executor instance */
- private static ScheduledThreadPoolExecutor executor; //@GuardedBy("EvictionTimer.class")
-
- /** Keys are weak references to tasks, values are runners managed by executor. */
- private static final HashMap<WeakReference<Runnable>, WeakRunner> taskMap = new HashMap<>(); // @GuardedBy("EvictionTimer.class")
-
- /** Prevents instantiation */
- private EvictionTimer() {
- // Hide the default constructor
- }
-
-
- /**
- * @since 2.4.3
- */
- @Override
- public String toString() {
- final StringBuilder builder = new StringBuilder();
- builder.append("EvictionTimer []");
- return builder.toString();
- }
-
- /**
- * Adds the specified eviction task to the timer. Tasks that are added with
- * a call to this method *must* call {@link
- * #cancel(BaseGenericObjectPool.Evictor, long, TimeUnit, boolean)}
- * to cancel the task to prevent memory and/or thread leaks in application
- * server environments.
- *
- * @param task Task to be scheduled.
- * @param delay Delay in milliseconds before task is executed.
- * @param period Time in milliseconds between executions.
- */
- static synchronized void schedule(
- final BaseGenericObjectPool<?>.Evictor task, final Duration delay, final Duration period) {
- if (null == executor) {
- executor = new ScheduledThreadPoolExecutor(1, new EvictorThreadFactory());
- executor.setRemoveOnCancelPolicy(true);
- executor.scheduleAtFixedRate(new Reaper(), delay.toMillis(), period.toMillis(), TimeUnit.MILLISECONDS);
- }
- final WeakReference<Runnable> ref = new WeakReference<>(task);
- final WeakRunner runner = new WeakRunner(ref);
- final ScheduledFuture<?> scheduledFuture = executor.scheduleWithFixedDelay(runner, delay.toMillis(),
- period.toMillis(), TimeUnit.MILLISECONDS);
- task.setScheduledFuture(scheduledFuture);
- taskMap.put(ref, runner);
- }
-
- /**
- * Removes the specified eviction task from the timer.
- *
- * @param evictor Task to be cancelled.
- * @param timeout If the associated executor is no longer required, how
- * long should this thread wait for the executor to
- * terminate?
- * @param restarting The state of the evictor.
- */
- static synchronized void cancel(final BaseGenericObjectPool<?>.Evictor evictor, final Duration timeout,
- final boolean restarting) {
- if (evictor != null) {
- evictor.cancel();
- remove(evictor);
- }
- if (!restarting && executor != null && taskMap.isEmpty()) {
- executor.shutdown();
- try {
- executor.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS);
- } catch (final InterruptedException e) {
- // Swallow
- // Significant API changes would be required to propagate this
- }
- executor.setCorePoolSize(0);
- executor = null;
- }
- }
-
- /**
- * Removes evictor from the task set and executor.
- * Only called when holding the class lock.
- *
- * @param evictor Eviction task to remove
- */
- private static void remove(final BaseGenericObjectPool<?>.Evictor evictor) {
- for (final Entry<WeakReference<Runnable>, WeakRunner> entry : taskMap.entrySet()) {
- if (entry.getKey().get() == evictor) {
- executor.remove(entry.getValue());
- taskMap.remove(entry.getKey());
- break;
- }
- }
- }
-
- /**
- * @return the number of eviction tasks under management.
- */
- static synchronized int getNumTasks() {
- return taskMap.size();
- }
-
/**
* Thread factory that creates a daemon thread, with the context class loader from this class.
*/
@@ -216,4 +117,103 @@ class EvictionTimer {
}
}
}
+
+
+ /** Executor instance */
+ private static ScheduledThreadPoolExecutor executor; //@GuardedBy("EvictionTimer.class")
+
+ /** Keys are weak references to tasks, values are runners managed by executor. */
+ private static final HashMap<WeakReference<Runnable>, WeakRunner> taskMap = new HashMap<>(); // @GuardedBy("EvictionTimer.class")
+
+ /**
+ * Removes the specified eviction task from the timer.
+ *
+ * @param evictor Task to be cancelled.
+ * @param timeout If the associated executor is no longer required, how
+ * long should this thread wait for the executor to
+ * terminate?
+ * @param restarting The state of the evictor.
+ */
+ static synchronized void cancel(final BaseGenericObjectPool<?>.Evictor evictor, final Duration timeout,
+ final boolean restarting) {
+ if (evictor != null) {
+ evictor.cancel();
+ remove(evictor);
+ }
+ if (!restarting && executor != null && taskMap.isEmpty()) {
+ executor.shutdown();
+ try {
+ executor.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS);
+ } catch (final InterruptedException e) {
+ // Swallow
+ // Significant API changes would be required to propagate this
+ }
+ executor.setCorePoolSize(0);
+ executor = null;
+ }
+ }
+
+ /**
+ * @return the number of eviction tasks under management.
+ */
+ static synchronized int getNumTasks() {
+ return taskMap.size();
+ }
+
+ /**
+ * Removes evictor from the task set and executor.
+ * Only called when holding the class lock.
+ *
+ * @param evictor Eviction task to remove
+ */
+ private static void remove(final BaseGenericObjectPool<?>.Evictor evictor) {
+ for (final Entry<WeakReference<Runnable>, WeakRunner> entry : taskMap.entrySet()) {
+ if (entry.getKey().get() == evictor) {
+ executor.remove(entry.getValue());
+ taskMap.remove(entry.getKey());
+ break;
+ }
+ }
+ }
+
+ /**
+ * Adds the specified eviction task to the timer. Tasks that are added with
+ * a call to this method *must* call {@link
+ * #cancel(BaseGenericObjectPool.Evictor, long, TimeUnit, boolean)}
+ * to cancel the task to prevent memory and/or thread leaks in application
+ * server environments.
+ *
+ * @param task Task to be scheduled.
+ * @param delay Delay in milliseconds before task is executed.
+ * @param period Time in milliseconds between executions.
+ */
+ static synchronized void schedule(
+ final BaseGenericObjectPool<?>.Evictor task, final Duration delay, final Duration period) {
+ if (null == executor) {
+ executor = new ScheduledThreadPoolExecutor(1, new EvictorThreadFactory());
+ executor.setRemoveOnCancelPolicy(true);
+ executor.scheduleAtFixedRate(new Reaper(), delay.toMillis(), period.toMillis(), TimeUnit.MILLISECONDS);
+ }
+ final WeakReference<Runnable> ref = new WeakReference<>(task);
+ final WeakRunner runner = new WeakRunner(ref);
+ final ScheduledFuture<?> scheduledFuture = executor.scheduleWithFixedDelay(runner, delay.toMillis(),
+ period.toMillis(), TimeUnit.MILLISECONDS);
+ task.setScheduledFuture(scheduledFuture);
+ taskMap.put(ref, runner);
+ }
+
+ /** Prevents instantiation */
+ private EvictionTimer() {
+ // Hide the default constructor
+ }
+
+ /**
+ * @since 2.4.3
+ */
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("EvictionTimer []");
+ return builder.toString();
+ }
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java b/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java
index 94a880a..3907fc7 100644
--- a/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java
+++ b/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java
@@ -87,6 +87,152 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
implements KeyedObjectPool<K, T>, GenericKeyedObjectPoolMXBean<K> {
/**
+ * Maintains information on the per key queue for a given key.
+ *
+ * @param <S> type of objects in the pool
+ */
+ private class ObjectDeque<S> {
+
+ private final LinkedBlockingDeque<PooledObject<S>> idleObjects;
+
+ /*
+ * Number of instances created - number destroyed.
+ * Invariant: createCount <= maxTotalPerKey
+ */
+ private final AtomicInteger createCount = new AtomicInteger(0);
+
+ private long makeObjectCount = 0;
+ private final Object makeObjectCountLock = new Object();
+
+ /*
+ * The map is keyed on pooled instances, wrapped to ensure that
+ * they work properly as keys.
+ */
+ private final Map<IdentityWrapper<S>, PooledObject<S>> allObjects =
+ new ConcurrentHashMap<>();
+
+ /*
+ * Number of threads with registered interest in this key.
+ * register(K) increments this counter and deRegister(K) decrements it.
+ * Invariant: empty keyed pool will not be dropped unless numInterested
+ * is 0.
+ */
+ private final AtomicLong numInterested = new AtomicLong(0);
+
+ /**
+ * Create a new ObjecDeque with the given fairness policy.
+ * @param fairness true means client threads waiting to borrow / return instances
+ * will be served as if waiting in a FIFO queue.
+ */
+ public ObjectDeque(final boolean fairness) {
+ idleObjects = new LinkedBlockingDeque<>(fairness);
+ }
+
+ /**
+ * Obtain all the objects for the current key.
+ *
+ * @return All the objects
+ */
+ public Map<IdentityWrapper<S>, PooledObject<S>> getAllObjects() {
+ return allObjects;
+ }
+
+ /**
+ * Obtain the count of the number of objects created for the current
+ * key.
+ *
+ * @return The number of objects created for this key
+ */
+ public AtomicInteger getCreateCount() {
+ return createCount;
+ }
+
+ /**
+ * Obtain the idle objects for the current key.
+ *
+ * @return The idle objects
+ */
+ public LinkedBlockingDeque<PooledObject<S>> getIdleObjects() {
+ return idleObjects;
+ }
+
+ /**
+ * Obtain the number of threads with an interest registered in this key.
+ *
+ * @return The number of threads with a registered interest in this key
+ */
+ public AtomicLong getNumInterested() {
+ return numInterested;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("ObjectDeque [idleObjects=");
+ builder.append(idleObjects);
+ builder.append(", createCount=");
+ builder.append(createCount);
+ builder.append(", allObjects=");
+ builder.append(allObjects);
+ builder.append(", numInterested=");
+ builder.append(numInterested);
+ builder.append("]");
+ return builder.toString();
+ }
+
+ }
+
+ // JMX specific attributes
+ private static final String ONAME_BASE =
+ "org.apache.commons.pool2:type=GenericKeyedObjectPool,name=";
+
+ //--- configuration attributes ---------------------------------------------
+ private volatile int maxIdlePerKey =
+ GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY;
+
+ private volatile int minIdlePerKey =
+ GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY;
+
+
+ private volatile int maxTotalPerKey =
+ GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY;
+
+ private final KeyedPooledObjectFactory<K, T> factory;
+
+ private final boolean fairness;
+
+ /*
+ * My hash of sub-pools (ObjectQueue). The list of keys <b>must</b> be kept
+ * in step with {@link #poolKeyList} using {@link #keyLock} to ensure any
+ * changes to the list of current keys is made in a thread-safe manner.
+ */
+ private final Map<K, ObjectDeque<T>> poolMap =
+ new ConcurrentHashMap<>(); // @GuardedBy("keyLock") for write access (and some read access)
+
+ /*
+ * List of pool keys - used to control eviction order. The list of keys
+ * <b>must</b> be kept in step with {@link #poolMap} using {@link #keyLock}
+ * to ensure any changes to the list of current keys is made in a
+ * thread-safe manner.
+ */
+ private final List<K> poolKeyList = new ArrayList<>(); // @GuardedBy("keyLock")
+
+ private final ReadWriteLock keyLock = new ReentrantReadWriteLock(true);
+
+ /*
+ * The combined count of the currently active objects for all keys and those
+ * in the process of being created. Under load, it may exceed
+ * {@link #maxTotal} but there will never be more than {@link #maxTotal}
+ * created at any one time.
+ */
+ private final AtomicInteger numTotal = new AtomicInteger(0);
+
+ private Iterator<K> evictionKeyIterator = null; // @GuardedBy("evictionLock")
+
+
+ private K evictionKey = null; // @GuardedBy("evictionLock")
+
+ /**
* Create a new {@code GenericKeyedObjectPool} using defaults from
* {@link GenericKeyedObjectPoolConfig}.
* @param factory the factory to be used to create entries
@@ -121,156 +267,64 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
}
/**
- * Gets the limit on the number of object instances allocated by the pool
- * (checked out or idle), per key. When the limit is reached, the sub-pool
- * is said to be exhausted. A negative value indicates no limit.
+ * Add an object to the set of idle objects for a given key.
*
- * @return the limit on the number of active instances per key
+ * @param key The key to associate with the idle object
+ * @param p The wrapped object to add.
*
- * @see #setMaxTotalPerKey
+ * @throws Exception If the associated factory fails to passivate the object
*/
- @Override
- public int getMaxTotalPerKey() {
- return maxTotalPerKey;
- }
+ private void addIdleObject(final K key, final PooledObject<T> p) throws Exception {
- /**
- * Sets the limit on the number of object instances allocated by the pool
- * (checked out or idle), per key. When the limit is reached, the sub-pool
- * is said to be exhausted. A negative value indicates no limit.
- *
- * @param maxTotalPerKey the limit on the number of active instances per key
- *
- * @see #getMaxTotalPerKey
- */
- public void setMaxTotalPerKey(final int maxTotalPerKey) {
- this.maxTotalPerKey = maxTotalPerKey;
+ if (p != null) {
+ factory.passivateObject(key, p);
+ final LinkedBlockingDeque<PooledObject<T>> idleObjects =
+ poolMap.get(key).getIdleObjects();
+ if (getLifo()) {
+ idleObjects.addFirst(p);
+ } else {
+ idleObjects.addLast(p);
+ }
+ }
}
/**
- * Gets the cap on the number of "idle" instances per key in the pool.
- * If maxIdlePerKey is set too low on heavily loaded systems it is possible
- * you will see objects being destroyed and almost immediately new objects
- * being created. This is a result of the active threads momentarily
- * returning objects faster than they are requesting them, causing the
- * number of idle objects to rise above maxIdlePerKey. The best value for
- * maxIdlePerKey for heavily loaded system will vary but the default is a
- * good starting point.
+ * Create an object using the {@link KeyedPooledObjectFactory#makeObject
+ * factory}, passivate it, and then place it in the idle object pool.
+ * {@code addObject} is useful for "pre-loading" a pool with idle
+ * objects.
*
- * @return the maximum number of "idle" instances that can be held in a
- * given keyed sub-pool or a negative value if there is no limit
+ * @param key the key a new instance should be added to
*
- * @see #setMaxIdlePerKey
+ * @throws Exception when {@link KeyedPooledObjectFactory#makeObject}
+ * fails.
*/
@Override
- public int getMaxIdlePerKey() {
- return maxIdlePerKey;
+ public void addObject(final K key) throws Exception {
+ assertOpen();
+ register(key);
+ try {
+ final PooledObject<T> p = create(key);
+ addIdleObject(key, p);
+ } finally {
+ deregister(key);
+ }
}
- /**
- * Sets the cap on the number of "idle" instances per key in the pool.
- * If maxIdlePerKey is set too low on heavily loaded systems it is possible
- * you will see objects being destroyed and almost immediately new objects
- * being created. This is a result of the active threads momentarily
- * returning objects faster than they are requesting them, causing the
- * number of idle objects to rise above maxIdlePerKey. The best value for
- * maxIdlePerKey for heavily loaded system will vary but the default is a
- * good starting point.
- *
- * @param maxIdlePerKey the maximum number of "idle" instances that can be
- * held in a given keyed sub-pool. Use a negative value
- * for no limit
- *
- * @see #getMaxIdlePerKey
- */
- public void setMaxIdlePerKey(final int maxIdlePerKey) {
- this.maxIdlePerKey = maxIdlePerKey;
- }
/**
- * Sets the target for the minimum number of idle objects to maintain in
- * each of the keyed sub-pools. This setting only has an effect if it is
- * positive and {@link #getTimeBetweenEvictionRunsMillis()} is greater than
- * zero. If this is the case, an attempt is made to ensure that each
- * sub-pool has the required minimum number of instances during idle object
- * eviction runs.
+ * Equivalent to <code>{@link #borrowObject(Object, long) borrowObject}(key,
+ * {@link #getMaxWaitMillis()})</code>.
* <p>
- * If the configured value of minIdlePerKey is greater than the configured
- * value for maxIdlePerKey then the value of maxIdlePerKey will be used
- * instead.
- *
- * @param minIdlePerKey The minimum size of the each keyed pool
- *
- * @see #getMinIdlePerKey
- * @see #getMaxIdlePerKey()
- * @see #setTimeBetweenEvictionRunsMillis
+ * {@inheritDoc}
*/
- public void setMinIdlePerKey(final int minIdlePerKey) {
- this.minIdlePerKey = minIdlePerKey;
- }
-
- /**
- * Gets the target for the minimum number of idle objects to maintain in
- * each of the keyed sub-pools. This setting only has an effect if it is
- * positive and {@link #getTimeBetweenEvictionRunsMillis()} is greater than
- * zero. If this is the case, an attempt is made to ensure that each
- * sub-pool has the required minimum number of instances during idle object
- * eviction runs.
- * <p>
- * If the configured value of minIdlePerKey is greater than the configured
- * value for maxIdlePerKey then the value of maxIdlePerKey will be used
- * instead.
- *
- * @return minimum size of the each keyed pool
- *
- * @see #setTimeBetweenEvictionRunsMillis
- */
- @Override
- public int getMinIdlePerKey() {
- final int maxIdlePerKeySave = getMaxIdlePerKey();
- if (this.minIdlePerKey > maxIdlePerKeySave) {
- return maxIdlePerKeySave;
- }
- return minIdlePerKey;
- }
-
- /**
- * Sets the configuration.
- *
- * @param conf the new configuration to use. This is used by value.
- *
- * @see GenericKeyedObjectPoolConfig
- */
- public void setConfig(final GenericKeyedObjectPoolConfig<T> conf) {
- super.setConfig(conf);
- setMaxIdlePerKey(conf.getMaxIdlePerKey());
- setMaxTotalPerKey(conf.getMaxTotalPerKey());
- setMaxTotal(conf.getMaxTotal());
- setMinIdlePerKey(conf.getMinIdlePerKey());
- }
-
- /**
- * Obtain a reference to the factory used to create, destroy and validate
- * the objects used by this pool.
- *
- * @return the factory
- */
- public KeyedPooledObjectFactory<K, T> getFactory() {
- return factory;
- }
-
- /**
- * Equivalent to <code>{@link #borrowObject(Object, long) borrowObject}(key,
- * {@link #getMaxWaitMillis()})</code>.
- * <p>
- * {@inheritDoc}
- */
- @Override
- public T borrowObject(final K key) throws Exception {
- return borrowObject(key, getMaxWaitMillis());
+ @Override
+ public T borrowObject(final K key) throws Exception {
+ return borrowObject(key, getMaxWaitMillis());
}
+
/**
* Borrows an object from the sub-pool associated with the given key using
* the specified waiting time which only applies if
@@ -427,176 +481,40 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
/**
- * Returns an object to a keyed sub-pool.
- * <p>
- * If {@link #getMaxIdlePerKey() maxIdle} is set to a positive value and the
- * number of idle instances under the given key has reached this value, the
- * returning instance is destroyed.
- * <p>
- * If {@link #getTestOnReturn() testOnReturn} == true, the returning
- * instance is validated before being returned to the idle instance sub-pool
- * under the given key. In this case, if validation fails, the instance is
- * destroyed.
- * <p>
- * Exceptions encountered destroying objects for any reason are swallowed
- * but notified via a {@link SwallowedExceptionListener}.
+ * Calculate the number of objects that need to be created to attempt to
+ * maintain the minimum number of idle objects while not exceeded the limits
+ * on the maximum number of objects either per key or totally.
*
- * @param key pool key
- * @param obj instance to return to the keyed pool
+ * @param objectDeque The set of objects to check
*
- * @throws IllegalStateException if an object is returned to the pool that
- * was not borrowed from it or if an object is
- * returned to the pool multiple times
+ * @return The number of new objects to create
*/
- @Override
- public void returnObject(final K key, final T obj) {
-
- final ObjectDeque<T> objectDeque = poolMap.get(key);
+ private int calculateDeficit(final ObjectDeque<T> objectDeque) {
if (objectDeque == null) {
- throw new IllegalStateException(
- "No keyed pool found under the given key.");
- }
-
- final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj));
-
- if (p == null) {
- throw new IllegalStateException(
- "Returned object not currently part of this pool");
+ return getMinIdlePerKey();
}
- markReturningState(p);
-
- final long activeTime = p.getActiveTimeMillis();
-
- try {
- if (getTestOnReturn() && !factory.validateObject(key, p)) {
- try {
- destroy(key, p, true, DestroyMode.NORMAL);
- } catch (final Exception e) {
- swallowException(e);
- }
- whenWaitersAddObject(key, objectDeque.idleObjects);
- return;
- }
-
- try {
- factory.passivateObject(key, p);
- } catch (final Exception e1) {
- swallowException(e1);
- try {
- destroy(key, p, true, DestroyMode.NORMAL);
- } catch (final Exception e) {
- swallowException(e);
- }
- whenWaitersAddObject(key, objectDeque.idleObjects);
- return;
- }
-
- if (!p.deallocate()) {
- throw new IllegalStateException(
- "Object has already been returned to this pool");
- }
-
- final int maxIdle = getMaxIdlePerKey();
- final LinkedBlockingDeque<PooledObject<T>> idleObjects =
- objectDeque.getIdleObjects();
+ // Used more than once so keep a local copy so the value is consistent
+ final int maxTotal = getMaxTotal();
+ final int maxTotalPerKeySave = getMaxTotalPerKey();
- if (isClosed() || maxIdle > -1 && maxIdle <= idleObjects.size()) {
- try {
- destroy(key, p, true, DestroyMode.NORMAL);
- } catch (final Exception e) {
- swallowException(e);
- }
- } else {
- if (getLifo()) {
- idleObjects.addFirst(p);
- } else {
- idleObjects.addLast(p);
- }
- if (isClosed()) {
- // Pool closed while object was being added to idle objects.
- // Make sure the returned object is destroyed rather than left
- // in the idle object pool (which would effectively be a leak)
- clear(key);
- }
- }
- } finally {
- if (hasBorrowWaiters()) {
- reuseCapacity();
- }
- updateStatsReturn(activeTime);
+ // Calculate no of objects needed to be created, in order to have
+ // the number of pooled objects < maxTotalPerKey();
+ int objectDefecit = getMinIdlePerKey() - objectDeque.getIdleObjects().size();
+ if (maxTotalPerKeySave > 0) {
+ final int growLimit = Math.max(0,
+ maxTotalPerKeySave - objectDeque.getIdleObjects().size());
+ objectDefecit = Math.min(objectDefecit, growLimit);
}
- }
- /**
- * Whether there is at least one thread waiting on this deque, add an pool object.
- * @param key pool key.
- * @param idleObjects list of idle pool objects.
- */
- private void whenWaitersAddObject(final K key, final LinkedBlockingDeque<PooledObject<T>> idleObjects) {
- if (idleObjects.hasTakeWaiters()) {
- try {
- addObject(key);
- } catch (final Exception e) {
- swallowException(e);
- }
+ // Take the maxTotal limit into account
+ if (maxTotal > 0) {
+ final int growLimit = Math.max(0, maxTotal - getNumActive() - getNumIdle());
+ objectDefecit = Math.min(objectDefecit, growLimit);
}
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Activation of this method decrements the active count associated with
- * the given keyed pool and attempts to destroy {@code obj.}
- *
- * @param key pool key
- * @param obj instance to invalidate
- *
- * @throws Exception if an exception occurs destroying the
- * object
- * @throws IllegalStateException if obj does not belong to the pool
- * under the given key
- */
- @Override
- public void invalidateObject(final K key, final T obj) throws Exception {
- invalidateObject(key, obj, DestroyMode.NORMAL);
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Activation of this method decrements the active count associated with
- * the given keyed pool and attempts to destroy {@code obj.}
- *
- * @param key pool key
- * @param obj instance to invalidate
- * @param mode DestroyMode context provided to factory
- *
- * @throws Exception if an exception occurs destroying the
- * object
- * @throws IllegalStateException if obj does not belong to the pool
- * under the given key
- * @since 2.9.0
- */
- @Override
- public void invalidateObject(final K key, final T obj, final DestroyMode mode) throws Exception {
-
- final ObjectDeque<T> objectDeque = poolMap.get(key);
- final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj));
- if (p == null) {
- throw new IllegalStateException(
- "Object not currently part of this pool");
- }
- synchronized (p) {
- if (p.getState() != PooledObjectState.INVALID) {
- destroy(key, p, true, mode);
- }
- }
- if (objectDeque.idleObjects.hasTakeWaiters()) {
- addObject(key);
- }
+ return objectDefecit;
}
@@ -661,40 +579,56 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
}
- @Override
- public int getNumActive() {
- return numTotal.get() - getNumIdle();
- }
-
+ /**
+ * Clears oldest 15% of objects in pool. The method sorts the objects into
+ * a TreeMap and then iterates the first 15% for removal.
+ */
+ public void clearOldest() {
- @Override
- public int getNumIdle() {
- final Iterator<ObjectDeque<T>> iter = poolMap.values().iterator();
- int result = 0;
+ // build sorted map of idle objects
+ final Map<PooledObject<T>, K> map = new TreeMap<>();
- while (iter.hasNext()) {
- result += iter.next().getIdleObjects().size();
+ for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
+ final K k = entry.getKey();
+ final ObjectDeque<T> deque = entry.getValue();
+ // Protect against possible NPE if key has been removed in another
+ // thread. Not worth locking the keys while this loop completes.
+ if (deque != null) {
+ final LinkedBlockingDeque<PooledObject<T>> idleObjects =
+ deque.getIdleObjects();
+ for (final PooledObject<T> p : idleObjects) {
+ // each item into the map using the PooledObject object as the
+ // key. It then gets sorted based on the idle time
+ map.put(p, k);
+ }
+ }
}
- return result;
- }
-
+ // Now iterate created map and kill the first 15% plus one to account
+ // for zero
+ int itemsToRemove = ((int) (map.size() * 0.15)) + 1;
+ final Iterator<Map.Entry<PooledObject<T>, K>> iter =
+ map.entrySet().iterator();
- @Override
- public int getNumActive(final K key) {
- final ObjectDeque<T> objectDeque = poolMap.get(key);
- if (objectDeque != null) {
- return objectDeque.getAllObjects().size() -
- objectDeque.getIdleObjects().size();
+ while (iter.hasNext() && itemsToRemove > 0) {
+ final Map.Entry<PooledObject<T>, K> entry = iter.next();
+ // kind of backwards on naming. In the map, each key is the
+ // PooledObject because it has the ordering with the timestamp
+ // value. Each value that the key references is the key of the
+ // list it belongs to.
+ final K key = entry.getValue();
+ final PooledObject<T> p = entry.getKey();
+ // Assume the destruction succeeds
+ boolean destroyed = true;
+ try {
+ destroyed = destroy(key, p, false, DestroyMode.NORMAL);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ if (destroyed) {
+ itemsToRemove--;
+ }
}
- return 0;
- }
-
-
- @Override
- public int getNumIdle(final K key) {
- final ObjectDeque<T> objectDeque = poolMap.get(key);
- return objectDeque != null ? objectDeque.getIdleObjects().size() : 0;
}
@@ -739,128 +673,227 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
}
}
-
/**
- * Clears oldest 15% of objects in pool. The method sorts the objects into
- * a TreeMap and then iterates the first 15% for removal.
+ * Create a new pooled object.
+ *
+ * @param key Key associated with new pooled object
+ *
+ * @return The new, wrapped pooled object
+ *
+ * @throws Exception If the objection creation fails
*/
- public void clearOldest() {
+ private PooledObject<T> create(final K key) throws Exception {
+ int maxTotalPerKeySave = getMaxTotalPerKey(); // Per key
+ if (maxTotalPerKeySave < 0) {
+ maxTotalPerKeySave = Integer.MAX_VALUE;
+ }
+ final int maxTotal = getMaxTotal(); // All keys
- // build sorted map of idle objects
- final Map<PooledObject<T>, K> map = new TreeMap<>();
+ final ObjectDeque<T> objectDeque = poolMap.get(key);
- for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
- final K k = entry.getKey();
- final ObjectDeque<T> deque = entry.getValue();
- // Protect against possible NPE if key has been removed in another
- // thread. Not worth locking the keys while this loop completes.
- if (deque != null) {
- final LinkedBlockingDeque<PooledObject<T>> idleObjects =
- deque.getIdleObjects();
- for (final PooledObject<T> p : idleObjects) {
- // each item into the map using the PooledObject object as the
- // key. It then gets sorted based on the idle time
- map.put(p, k);
+ // Check against the overall limit
+ boolean loop = true;
+
+ while (loop) {
+ final int newNumTotal = numTotal.incrementAndGet();
+ if (maxTotal > -1 && newNumTotal > maxTotal) {
+ numTotal.decrementAndGet();
+ if (getNumIdle() == 0) {
+ return null;
}
+ clearOldest();
+ } else {
+ loop = false;
}
}
- // Now iterate created map and kill the first 15% plus one to account
- // for zero
- int itemsToRemove = ((int) (map.size() * 0.15)) + 1;
- final Iterator<Map.Entry<PooledObject<T>, K>> iter =
- map.entrySet().iterator();
+ // Flag that indicates if create should:
+ // - TRUE: call the factory to create an object
+ // - FALSE: return null
+ // - null: loop and re-test the condition that determines whether to
+ // call the factory
+ Boolean create = null;
+ while (create == null) {
+ synchronized (objectDeque.makeObjectCountLock) {
+ final long newCreateCount = objectDeque.getCreateCount().incrementAndGet();
+ // Check against the per key limit
+ if (newCreateCount > maxTotalPerKeySave) {
+ // The key is currently at capacity or in the process of
+ // making enough new objects to take it to capacity.
+ objectDeque.getCreateCount().decrementAndGet();
+ if (objectDeque.makeObjectCount == 0) {
+ // There are no makeObject() calls in progress for this
+ // key so the key is at capacity. Do not attempt to
+ // create a new object. Return and wait for an object to
+ // be returned.
+ create = Boolean.FALSE;
+ } else {
+ // There are makeObject() calls in progress that might
+ // bring the pool to capacity. Those calls might also
+ // fail so wait until they complete and then re-test if
+ // the pool is at capacity or not.
+ objectDeque.makeObjectCountLock.wait();
+ }
+ } else {
+ // The pool is not at capacity. Create a new object.
+ objectDeque.makeObjectCount++;
+ create = Boolean.TRUE;
+ }
+ }
+ }
- while (iter.hasNext() && itemsToRemove > 0) {
- final Map.Entry<PooledObject<T>, K> entry = iter.next();
- // kind of backwards on naming. In the map, each key is the
- // PooledObject because it has the ordering with the timestamp
- // value. Each value that the key references is the key of the
- // list it belongs to.
- final K key = entry.getValue();
- final PooledObject<T> p = entry.getKey();
- // Assume the destruction succeeds
- boolean destroyed = true;
- try {
- destroyed = destroy(key, p, false, DestroyMode.NORMAL);
- } catch (final Exception e) {
- swallowException(e);
+ if (!create.booleanValue()) {
+ numTotal.decrementAndGet();
+ return null;
+ }
+
+ PooledObject<T> p = null;
+ try {
+ p = factory.makeObject(key);
+ if (getTestOnCreate() && !factory.validateObject(key, p)) {
+ numTotal.decrementAndGet();
+ objectDeque.getCreateCount().decrementAndGet();
+ return null;
}
- if (destroyed) {
- itemsToRemove--;
+ } catch (final Exception e) {
+ numTotal.decrementAndGet();
+ objectDeque.getCreateCount().decrementAndGet();
+ throw e;
+ } finally {
+ synchronized (objectDeque.makeObjectCountLock) {
+ objectDeque.makeObjectCount--;
+ objectDeque.makeObjectCountLock.notifyAll();
}
}
+
+ createdCount.incrementAndGet();
+ objectDeque.getAllObjects().put(new IdentityWrapper<>(p.getObject()), p);
+ return p;
}
/**
- * Attempt to create one new instance to serve from the most heavily
- * loaded pool that can add a new instance.
- *
- * This method exists to ensure liveness in the pool when threads are
- * parked waiting and capacity to create instances under the requested keys
- * subsequently becomes available.
+ * De-register the use of a key by an object.
+ * <p>
+ * register() and deregister() must always be used as a pair.
*
- * This method is not guaranteed to create an instance and its selection
- * of the most loaded pool that can create an instance may not always be
- * correct, since it does not lock the pool and instances may be created,
- * borrowed, returned or destroyed by other threads while it is executing.
+ * @param k The key to de-register
*/
- private void reuseCapacity() {
- final int maxTotalPerKeySave = getMaxTotalPerKey();
-
- // Find the most loaded pool that could take a new instance
- int maxQueueLength = 0;
- LinkedBlockingDeque<PooledObject<T>> mostLoaded = null;
- K loadedKey = null;
- for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
- final K k = entry.getKey();
- final ObjectDeque<T> deque = entry.getValue();
- if (deque != null) {
- final LinkedBlockingDeque<PooledObject<T>> pool = deque.getIdleObjects();
- final int queueLength = pool.getTakeQueueLength();
- if (getNumActive(k) < maxTotalPerKeySave && queueLength > maxQueueLength) {
- maxQueueLength = queueLength;
- mostLoaded = pool;
- loadedKey = k;
- }
- }
- }
-
- // Attempt to add an instance to the most loaded pool
- if (mostLoaded != null) {
- register(loadedKey);
- try {
- final PooledObject<T> p = create(loadedKey);
- if (p != null) {
- addIdleObject(loadedKey, p);
+ private void deregister(final K k) {
+ Lock lock = keyLock.readLock();
+ try {
+ lock.lock();
+ final ObjectDeque<T> objectDeque = poolMap.get(k);
+ final long numInterested = objectDeque.getNumInterested().decrementAndGet();
+ if (numInterested == 0 && objectDeque.getCreateCount().get() == 0) {
+ // Potential to remove key
+ // Upgrade to write lock
+ lock.unlock();
+ lock = keyLock.writeLock();
+ lock.lock();
+ if (objectDeque.getCreateCount().get() == 0 && objectDeque.getNumInterested().get() == 0) {
+ // NOTE: Keys must always be removed from both poolMap and
+ // poolKeyList at the same time while protected by
+ // keyLock.writeLock()
+ poolMap.remove(k);
+ poolKeyList.remove(k);
}
- } catch (final Exception e) {
- swallowException(e);
- } finally {
- deregister(loadedKey);
}
+ } finally {
+ lock.unlock();
}
}
+
/**
- * Checks to see if there are any threads currently waiting to borrow
- * objects but are blocked waiting for more objects to become available.
+ * Destroy the wrapped, pooled object.
*
- * @return {@code true} if there is at least one thread waiting otherwise
- * {@code false}
- */
- private boolean hasBorrowWaiters() {
- for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
- final ObjectDeque<T> deque = entry.getValue();
- if (deque != null) {
- final LinkedBlockingDeque<PooledObject<T>> pool =
- deque.getIdleObjects();
- if(pool.hasTakeWaiters()) {
- return true;
+ * @param key The key associated with the object to destroy.
+ * @param toDestroy The wrapped object to be destroyed
+ * @param always Should the object be destroyed even if it is not currently
+ * in the set of idle objects for the given key
+ * @param mode DestroyMode context provided to the factory
+ *
+ * @return {@code true} if the object was destroyed, otherwise {@code false}
+ * @throws Exception If the object destruction failed
+ */
+ private boolean destroy(final K key, final PooledObject<T> toDestroy, final boolean always, final DestroyMode mode)
+ throws Exception {
+
+ final ObjectDeque<T> objectDeque = register(key);
+
+ try {
+ boolean isIdle;
+ synchronized(toDestroy) {
+ // Check idle state directly
+ isIdle = toDestroy.getState().equals(PooledObjectState.IDLE);
+ // If idle, not under eviction test, or always is true, remove instance,
+ // updating isIdle if instance is found in idle objects
+ if (isIdle || always) {
+ isIdle = objectDeque.getIdleObjects().remove(toDestroy);
+ }
+ }
+ if (isIdle || always) {
+ objectDeque.getAllObjects().remove(new IdentityWrapper<>(toDestroy.getObject()));
+ toDestroy.invalidate();
+
+ try {
+ factory.destroyObject(key, toDestroy, mode);
+ } finally {
+ objectDeque.getCreateCount().decrementAndGet();
+ destroyedCount.incrementAndGet();
+ numTotal.decrementAndGet();
}
+ return true;
+ }
+ return false;
+ } finally {
+ deregister(key);
+ }
+ }
+
+ @Override
+ void ensureMinIdle() throws Exception {
+ final int minIdlePerKeySave = getMinIdlePerKey();
+ if (minIdlePerKeySave < 1) {
+ return;
+ }
+
+ for (final K k : poolMap.keySet()) {
+ ensureMinIdle(k);
+ }
+ }
+
+ /**
+ * Ensure that the configured number of minimum idle objects is available in
+ * the pool for the given key.
+ *
+ * @param key The key to check for idle objects
+ *
+ * @throws Exception If a new object is required and cannot be created
+ */
+ private void ensureMinIdle(final K key) throws Exception {
+ // Calculate current pool objects
+ ObjectDeque<T> objectDeque = poolMap.get(key);
+
+ // objectDeque == null is OK here. It is handled correctly by both
+ // methods called below.
+
+ // this method isn't synchronized so the
+ // calculateDeficit is done at the beginning
+ // as a loop limit and a second time inside the loop
+ // to stop when another thread already returned the
+ // needed objects
+ final int deficit = calculateDeficit(objectDeque);
+
+ for (int i = 0; i < deficit && calculateDeficit(objectDeque) > 0; i++) {
+ addObject(key);
+ // If objectDeque was null, it won't be any more. Obtain a reference
+ // to it so the deficit can be correctly calculated. It needs to
+ // take account of objects created in other threads.
+ if (objectDeque == null) {
+ objectDeque = poolMap.get(key);
}
}
- return false;
}
@@ -995,151 +1028,318 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
}
/**
- * Create a new pooled object.
+ * Obtain a reference to the factory used to create, destroy and validate
+ * the objects used by this pool.
*
- * @param key Key associated with new pooled object
+ * @return the factory
+ */
+ public KeyedPooledObjectFactory<K, T> getFactory() {
+ return factory;
+ }
+
+ /**
+ * Gets the cap on the number of "idle" instances per key in the pool.
+ * If maxIdlePerKey is set too low on heavily loaded systems it is possible
+ * you will see objects being destroyed and almost immediately new objects
+ * being created. This is a result of the active threads momentarily
+ * returning objects faster than they are requesting them, causing the
+ * number of idle objects to rise above maxIdlePerKey. The best value for
+ * maxIdlePerKey for heavily loaded system will vary but the default is a
+ * good starting point.
*
- * @return The new, wrapped pooled object
+ * @return the maximum number of "idle" instances that can be held in a
+ * given keyed sub-pool or a negative value if there is no limit
*
- * @throws Exception If the objection creation fails
+ * @see #setMaxIdlePerKey
*/
- private PooledObject<T> create(final K key) throws Exception {
- int maxTotalPerKeySave = getMaxTotalPerKey(); // Per key
- if (maxTotalPerKeySave < 0) {
- maxTotalPerKeySave = Integer.MAX_VALUE;
+ @Override
+ public int getMaxIdlePerKey() {
+ return maxIdlePerKey;
+ }
+
+ /**
+ * Gets the limit on the number of object instances allocated by the pool
+ * (checked out or idle), per key. When the limit is reached, the sub-pool
+ * is said to be exhausted. A negative value indicates no limit.
+ *
+ * @return the limit on the number of active instances per key
+ *
+ * @see #setMaxTotalPerKey
+ */
+ @Override
+ public int getMaxTotalPerKey() {
+ return maxTotalPerKey;
+ }
+
+ /**
+ * Gets the target for the minimum number of idle objects to maintain in
+ * each of the keyed sub-pools. This setting only has an effect if it is
+ * positive and {@link #getTimeBetweenEvictionRunsMillis()} is greater than
+ * zero. If this is the case, an attempt is made to ensure that each
+ * sub-pool has the required minimum number of instances during idle object
+ * eviction runs.
+ * <p>
+ * If the configured value of minIdlePerKey is greater than the configured
+ * value for maxIdlePerKey then the value of maxIdlePerKey will be used
+ * instead.
+ *
+ * @return minimum size of the each keyed pool
+ *
+ * @see #setTimeBetweenEvictionRunsMillis
+ */
+ @Override
+ public int getMinIdlePerKey() {
+ final int maxIdlePerKeySave = getMaxIdlePerKey();
+ if (this.minIdlePerKey > maxIdlePerKeySave) {
+ return maxIdlePerKeySave;
}
- final int maxTotal = getMaxTotal(); // All keys
+ return minIdlePerKey;
+ }
+
+ @Override
+ public int getNumActive() {
+ return numTotal.get() - getNumIdle();
+ }
+ @Override
+ public int getNumActive(final K key) {
final ObjectDeque<T> objectDeque = poolMap.get(key);
+ if (objectDeque != null) {
+ return objectDeque.getAllObjects().size() -
+ objectDeque.getIdleObjects().size();
+ }
+ return 0;
+ }
- // Check against the overall limit
- boolean loop = true;
+ @Override
+ public Map<String,Integer> getNumActivePerKey() {
+ final HashMap<String,Integer> result = new HashMap<>();
- while (loop) {
- final int newNumTotal = numTotal.incrementAndGet();
- if (maxTotal > -1 && newNumTotal > maxTotal) {
- numTotal.decrementAndGet();
- if (getNumIdle() == 0) {
- return null;
+ final Iterator<Entry<K,ObjectDeque<T>>> iter = poolMap.entrySet().iterator();
+ while (iter.hasNext()) {
+ final Entry<K,ObjectDeque<T>> entry = iter.next();
+ if (entry != null) {
+ final K key = entry.getKey();
+ final ObjectDeque<T> objectDequeue = entry.getValue();
+ if (key != null && objectDequeue != null) {
+ result.put(key.toString(), Integer.valueOf(
+ objectDequeue.getAllObjects().size() -
+ objectDequeue.getIdleObjects().size()));
}
- clearOldest();
- } else {
- loop = false;
}
}
+ return result;
+ }
- // Flag that indicates if create should:
- // - TRUE: call the factory to create an object
- // - FALSE: return null
- // - null: loop and re-test the condition that determines whether to
- // call the factory
- Boolean create = null;
- while (create == null) {
- synchronized (objectDeque.makeObjectCountLock) {
- final long newCreateCount = objectDeque.getCreateCount().incrementAndGet();
- // Check against the per key limit
- if (newCreateCount > maxTotalPerKeySave) {
- // The key is currently at capacity or in the process of
- // making enough new objects to take it to capacity.
- objectDeque.getCreateCount().decrementAndGet();
- if (objectDeque.makeObjectCount == 0) {
- // There are no makeObject() calls in progress for this
- // key so the key is at capacity. Do not attempt to
- // create a new object. Return and wait for an object to
- // be returned.
- create = Boolean.FALSE;
- } else {
- // There are makeObject() calls in progress that might
- // bring the pool to capacity. Those calls might also
- // fail so wait until they complete and then re-test if
- // the pool is at capacity or not.
- objectDeque.makeObjectCountLock.wait();
- }
- } else {
- // The pool is not at capacity. Create a new object.
- objectDeque.makeObjectCount++;
- create = Boolean.TRUE;
- }
- }
- }
+ @Override
+ public int getNumIdle() {
+ final Iterator<ObjectDeque<T>> iter = poolMap.values().iterator();
+ int result = 0;
- if (!create.booleanValue()) {
- numTotal.decrementAndGet();
- return null;
+ while (iter.hasNext()) {
+ result += iter.next().getIdleObjects().size();
}
- PooledObject<T> p = null;
- try {
- p = factory.makeObject(key);
- if (getTestOnCreate() && !factory.validateObject(key, p)) {
- numTotal.decrementAndGet();
- objectDeque.getCreateCount().decrementAndGet();
- return null;
- }
- } catch (final Exception e) {
- numTotal.decrementAndGet();
- objectDeque.getCreateCount().decrementAndGet();
- throw e;
- } finally {
- synchronized (objectDeque.makeObjectCountLock) {
- objectDeque.makeObjectCount--;
- objectDeque.makeObjectCountLock.notifyAll();
- }
- }
+ return result;
+ }
- createdCount.incrementAndGet();
- objectDeque.getAllObjects().put(new IdentityWrapper<>(p.getObject()), p);
- return p;
+
+ //--- JMX support ----------------------------------------------------------
+
+ @Override
+ public int getNumIdle(final K key) {
+ final ObjectDeque<T> objectDeque = poolMap.get(key);
+ return objectDeque != null ? objectDeque.getIdleObjects().size() : 0;
}
/**
- * Destroy the wrapped, pooled object.
+ * Calculate the number of objects to test in a run of the idle object
+ * evictor.
*
- * @param key The key associated with the object to destroy.
- * @param toDestroy The wrapped object to be destroyed
- * @param always Should the object be destroyed even if it is not currently
- * in the set of idle objects for the given key
- * @param mode DestroyMode context provided to the factory
+ * @return The number of objects to test for validity
+ */
+ private int getNumTests() {
+ final int totalIdle = getNumIdle();
+ final int numTests = getNumTestsPerEvictionRun();
+ if (numTests >= 0) {
+ return Math.min(numTests, totalIdle);
+ }
+ return(int)(Math.ceil(totalIdle/Math.abs((double)numTests)));
+ }
+
+ /**
+ * Return an estimate of the number of threads currently blocked waiting for
+ * an object from the pool. This is intended for monitoring only, not for
+ * synchronization control.
*
- * @return {@code true} if the object was destroyed, otherwise {@code false}
- * @throws Exception If the object destruction failed
+ * @return The estimate of the number of threads currently blocked waiting
+ * for an object from the pool
*/
- private boolean destroy(final K key, final PooledObject<T> toDestroy, final boolean always, final DestroyMode mode)
- throws Exception {
+ @Override
+ public int getNumWaiters() {
+ int result = 0;
- final ObjectDeque<T> objectDeque = register(key);
+ if (getBlockWhenExhausted()) {
+ final Iterator<ObjectDeque<T>> iter = poolMap.values().iterator();
- try {
- boolean isIdle;
- synchronized(toDestroy) {
- // Check idle state directly
- isIdle = toDestroy.getState().equals(PooledObjectState.IDLE);
- // If idle, not under eviction test, or always is true, remove instance,
- // updating isIdle if instance is found in idle objects
- if (isIdle || always) {
- isIdle = objectDeque.getIdleObjects().remove(toDestroy);
+ while (iter.hasNext()) {
+ // Assume no overflow
+ result += iter.next().getIdleObjects().getTakeQueueLength();
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Return an estimate of the number of threads currently blocked waiting for
+ * an object from the pool for each key. This is intended for
+ * monitoring only, not for synchronization control.
+ *
+ * @return The estimate of the number of threads currently blocked waiting
+ * for an object from the pool for each key
+ */
+ @Override
+ public Map<String,Integer> getNumWaitersByKey() {
+ final Map<String,Integer> result = new HashMap<>();
+
+ for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
+ final K k = entry.getKey();
+ final ObjectDeque<T> deque = entry.getValue();
+ if (deque != null) {
+ if (getBlockWhenExhausted()) {
+ result.put(k.toString(), Integer.valueOf(
+ deque.getIdleObjects().getTakeQueueLength()));
+ } else {
+ result.put(k.toString(), Integer.valueOf(0));
}
}
- if (isIdle || always) {
- objectDeque.getAllObjects().remove(new IdentityWrapper<>(toDestroy.getObject()));
- toDestroy.invalidate();
+ }
+ return result;
+ }
- try {
- factory.destroyObject(key, toDestroy, mode);
- } finally {
- objectDeque.getCreateCount().decrementAndGet();
- destroyedCount.incrementAndGet();
- numTotal.decrementAndGet();
+
+ //--- inner classes ----------------------------------------------
+
+ /**
+ * Checks to see if there are any threads currently waiting to borrow
+ * objects but are blocked waiting for more objects to become available.
+ *
+ * @return {@code true} if there is at least one thread waiting otherwise
+ * {@code false}
+ */
+ private boolean hasBorrowWaiters() {
+ for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
+ final ObjectDeque<T> deque = entry.getValue();
+ if (deque != null) {
+ final LinkedBlockingDeque<PooledObject<T>> pool =
+ deque.getIdleObjects();
+ if(pool.hasTakeWaiters()) {
+ return true;
}
- return true;
}
- return false;
- } finally {
- deregister(key);
}
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * Activation of this method decrements the active count associated with
+ * the given keyed pool and attempts to destroy {@code obj.}
+ *
+ * @param key pool key
+ * @param obj instance to invalidate
+ *
+ * @throws Exception if an exception occurs destroying the
+ * object
+ * @throws IllegalStateException if obj does not belong to the pool
+ * under the given key
+ */
+ @Override
+ public void invalidateObject(final K key, final T obj) throws Exception {
+ invalidateObject(key, obj, DestroyMode.NORMAL);
}
+ /**
+ * {@inheritDoc}
+ * <p>
+ * Activation of this method decrements the active count associated with
+ * the given keyed pool and attempts to destroy {@code obj.}
+ *
+ * @param key pool key
+ * @param obj instance to invalidate
+ * @param mode DestroyMode context provided to factory
+ *
+ * @throws Exception if an exception occurs destroying the
+ * object
+ * @throws IllegalStateException if obj does not belong to the pool
+ * under the given key
+ * @since 2.9.0
+ */
+ @Override
+ public void invalidateObject(final K key, final T obj, final DestroyMode mode) throws Exception {
+ final ObjectDeque<T> objectDeque = poolMap.get(key);
+
+ final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj));
+ if (p == null) {
+ throw new IllegalStateException(
+ "Object not currently part of this pool");
+ }
+ synchronized (p) {
+ if (p.getState() != PooledObjectState.INVALID) {
+ destroy(key, p, true, mode);
+ }
+ }
+ if (objectDeque.idleObjects.hasTakeWaiters()) {
+ addObject(key);
+ }
+ }
+ /**
+ * Provides information on all the objects in the pool, both idle (waiting
+ * to be borrowed) and active (currently borrowed).
+ * <p>
+ * Note: This is named listAllObjects so it is presented as an operation via
+ * JMX. That means it won't be invoked unless the explicitly requested
+ * whereas all attributes will be automatically requested when viewing the
+ * attributes for an object in a tool like JConsole.
+ *
+ * @return Information grouped by key on all the objects in the pool
+ */
+ @Override
+ public Map<String,List<DefaultPooledObjectInfo>> listAllObjects() {
+ final Map<String,List<DefaultPooledObjectInfo>> result =
+ new HashMap<>();
+ for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
+ final K k = entry.getKey();
+ final ObjectDeque<T> deque = entry.getValue();
+ if (deque != null) {
+ final List<DefaultPooledObjectInfo> list =
+ new ArrayList<>();
+ result.put(k.toString(), list);
+ for (final PooledObject<T> p : deque.getAllObjects().values()) {
+ list.add(new DefaultPooledObjectInfo(p));
+ }
+ }
+ }
+ return result;
+ }
+ /**
+ * Registers a key for pool control and ensures that
+ * {@link #getMinIdlePerKey()} idle instances are created.
+ *
+ * @param key - The key to register for pool control.
+ *
+ * @throws Exception If the associated factory throws an exception
+ */
+ public void preparePool(final K key) throws Exception {
+ final int minIdlePerKeySave = getMinIdlePerKey();
+ if (minIdlePerKeySave < 1) {
+ return;
+ }
+ ensureMinIdle(key);
+ }
/**
* Register the use of a key by an object.
* <p>
@@ -1183,441 +1383,226 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
return objectDeque;
}
+
+ //--- internal attributes --------------------------------------------------
+
/**
- * De-register the use of a key by an object.
+ * Returns an object to a keyed sub-pool.
* <p>
- * register() and deregister() must always be used as a pair.
+ * If {@link #getMaxIdlePerKey() maxIdle} is set to a positive value and the
+ * number of idle instances under the given key has reached this value, the
+ * returning instance is destroyed.
+ * <p>
+ * If {@link #getTestOnReturn() testOnReturn} == true, the returning
+ * instance is validated before being returned to the idle instance sub-pool
+ * under the given key. In this case, if validation fails, the instance is
+ * destroyed.
+ * <p>
+ * Exceptions encountered destroying objects for any reason are swallowed
+ * but notified via a {@link SwallowedExceptionListener}.
*
- * @param k The key to de-register
- */
- private void deregister(final K k) {
- Lock lock = keyLock.readLock();
- try {
- lock.lock();
- final ObjectDeque<T> objectDeque = poolMap.get(k);
- final long numInterested = objectDeque.getNumInterested().decrementAndGet();
- if (numInterested == 0 && objectDeque.getCreateCount().get() == 0) {
- // Potential to remove key
- // Upgrade to write lock
- lock.unlock();
- lock = keyLock.writeLock();
- lock.lock();
- if (objectDeque.getCreateCount().get() == 0 && objectDeque.getNumInterested().get() == 0) {
- // NOTE: Keys must always be removed from both poolMap and
- // poolKeyList at the same time while protected by
- // keyLock.writeLock()
- poolMap.remove(k);
- poolKeyList.remove(k);
- }
- }
- } finally {
- lock.unlock();
- }
- }
-
- @Override
- void ensureMinIdle() throws Exception {
- final int minIdlePerKeySave = getMinIdlePerKey();
- if (minIdlePerKeySave < 1) {
- return;
- }
-
- for (final K k : poolMap.keySet()) {
- ensureMinIdle(k);
- }
- }
-
- /**
- * Ensure that the configured number of minimum idle objects is available in
- * the pool for the given key.
- *
- * @param key The key to check for idle objects
- *
- * @throws Exception If a new object is required and cannot be created
- */
- private void ensureMinIdle(final K key) throws Exception {
- // Calculate current pool objects
- ObjectDeque<T> objectDeque = poolMap.get(key);
-
- // objectDeque == null is OK here. It is handled correctly by both
- // methods called below.
-
- // this method isn't synchronized so the
- // calculateDeficit is done at the beginning
- // as a loop limit and a second time inside the loop
- // to stop when another thread already returned the
- // needed objects
- final int deficit = calculateDeficit(objectDeque);
-
- for (int i = 0; i < deficit && calculateDeficit(objectDeque) > 0; i++) {
- addObject(key);
- // If objectDeque was null, it won't be any more. Obtain a reference
- // to it so the deficit can be correctly calculated. It needs to
- // take account of objects created in other threads.
- if (objectDeque == null) {
- objectDeque = poolMap.get(key);
- }
- }
- }
-
- /**
- * Create an object using the {@link KeyedPooledObjectFactory#makeObject
- * factory}, passivate it, and then place it in the idle object pool.
- * {@code addObject} is useful for "pre-loading" a pool with idle
- * objects.
- *
- * @param key the key a new instance should be added to
- *
- * @throws Exception when {@link KeyedPooledObjectFactory#makeObject}
- * fails.
+ * @param key pool key
+ * @param obj instance to return to the keyed pool
+ *
+ * @throws IllegalStateException if an object is returned to the pool that
+ * was not borrowed from it or if an object is
+ * returned to the pool multiple times
*/
@Override
- public void addObject(final K key) throws Exception {
- assertOpen();
- register(key);
- try {
- final PooledObject<T> p = create(key);
- addIdleObject(key, p);
- } finally {
- deregister(key);
- }
- }
-
- /**
- * Add an object to the set of idle objects for a given key.
- *
- * @param key The key to associate with the idle object
- * @param p The wrapped object to add.
- *
- * @throws Exception If the associated factory fails to passivate the object
- */
- private void addIdleObject(final K key, final PooledObject<T> p) throws Exception {
-
- if (p != null) {
- factory.passivateObject(key, p);
- final LinkedBlockingDeque<PooledObject<T>> idleObjects =
- poolMap.get(key).getIdleObjects();
- if (getLifo()) {
- idleObjects.addFirst(p);
- } else {
- idleObjects.addLast(p);
- }
- }
- }
-
- /**
- * Registers a key for pool control and ensures that
- * {@link #getMinIdlePerKey()} idle instances are created.
- *
- * @param key - The key to register for pool control.
- *
- * @throws Exception If the associated factory throws an exception
- */
- public void preparePool(final K key) throws Exception {
- final int minIdlePerKeySave = getMinIdlePerKey();
- if (minIdlePerKeySave < 1) {
- return;
- }
- ensureMinIdle(key);
- }
-
- /**
- * Calculate the number of objects to test in a run of the idle object
- * evictor.
- *
- * @return The number of objects to test for validity
- */
- private int getNumTests() {
- final int totalIdle = getNumIdle();
- final int numTests = getNumTestsPerEvictionRun();
- if (numTests >= 0) {
- return Math.min(numTests, totalIdle);
- }
- return(int)(Math.ceil(totalIdle/Math.abs((double)numTests)));
- }
+ public void returnObject(final K key, final T obj) {
- /**
- * Calculate the number of objects that need to be created to attempt to
- * maintain the minimum number of idle objects while not exceeded the limits
- * on the maximum number of objects either per key or totally.
- *
- * @param objectDeque The set of objects to check
- *
- * @return The number of new objects to create
- */
- private int calculateDeficit(final ObjectDeque<T> objectDeque) {
+ final ObjectDeque<T> objectDeque = poolMap.get(key);
if (objectDeque == null) {
- return getMinIdlePerKey();
+ throw new IllegalStateException(
+ "No keyed pool found under the given key.");
}
- // Used more than once so keep a local copy so the value is consistent
- final int maxTotal = getMaxTotal();
- final int maxTotalPerKeySave = getMaxTotalPerKey();
-
- // Calculate no of objects needed to be created, in order to have
- // the number of pooled objects < maxTotalPerKey();
- int objectDefecit = getMinIdlePerKey() - objectDeque.getIdleObjects().size();
- if (maxTotalPerKeySave > 0) {
- final int growLimit = Math.max(0,
- maxTotalPerKeySave - objectDeque.getIdleObjects().size());
- objectDefecit = Math.min(objectDefecit, growLimit);
- }
+ final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj));
- // Take the maxTotal limit into account
- if (maxTotal > 0) {
- final int growLimit = Math.max(0, maxTotal - getNumActive() - getNumIdle());
- objectDefecit = Math.min(objectDefecit, growLimit);
+ if (p == null) {
+ throw new IllegalStateException(
+ "Returned object not currently part of this pool");
}
- return objectDefecit;
- }
-
-
- //--- JMX support ----------------------------------------------------------
+ markReturningState(p);
- @Override
- public Map<String,Integer> getNumActivePerKey() {
- final HashMap<String,Integer> result = new HashMap<>();
+ final long activeTime = p.getActiveTimeMillis();
- final Iterator<Entry<K,ObjectDeque<T>>> iter = poolMap.entrySet().iterator();
- while (iter.hasNext()) {
- final Entry<K,ObjectDeque<T>> entry = iter.next();
- if (entry != null) {
- final K key = entry.getKey();
- final ObjectDeque<T> objectDequeue = entry.getValue();
- if (key != null && objectDequeue != null) {
- result.put(key.toString(), Integer.valueOf(
- objectDequeue.getAllObjects().size() -
- objectDequeue.getIdleObjects().size()));
+ try {
+ if (getTestOnReturn() && !factory.validateObject(key, p)) {
+ try {
+ destroy(key, p, true, DestroyMode.NORMAL);
+ } catch (final Exception e) {
+ swallowException(e);
}
+ whenWaitersAddObject(key, objectDeque.idleObjects);
+ return;
}
- }
- return result;
- }
-
- /**
- * Return an estimate of the number of threads currently blocked waiting for
- * an object from the pool. This is intended for monitoring only, not for
- * synchronization control.
- *
- * @return The estimate of the number of threads currently blocked waiting
- * for an object from the pool
- */
- @Override
- public int getNumWaiters() {
- int result = 0;
- if (getBlockWhenExhausted()) {
- final Iterator<ObjectDeque<T>> iter = poolMap.values().iterator();
-
- while (iter.hasNext()) {
- // Assume no overflow
- result += iter.next().getIdleObjects().getTakeQueueLength();
+ try {
+ factory.passivateObject(key, p);
+ } catch (final Exception e1) {
+ swallowException(e1);
+ try {
+ destroy(key, p, true, DestroyMode.NORMAL);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ whenWaitersAddObject(key, objectDeque.idleObjects);
+ return;
}
- }
- return result;
- }
+ if (!p.deallocate()) {
+ throw new IllegalStateException(
+ "Object has already been returned to this pool");
+ }
- /**
- * Return an estimate of the number of threads currently blocked waiting for
- * an object from the pool for each key. This is intended for
- * monitoring only, not for synchronization control.
- *
- * @return The estimate of the number of threads currently blocked waiting
- * for an object from the pool for each key
- */
- @Override
- public Map<String,Integer> getNumWaitersByKey() {
- final Map<String,Integer> result = new HashMap<>();
+ final int maxIdle = getMaxIdlePerKey();
+ final LinkedBlockingDeque<PooledObject<T>> idleObjects =
+ objectDeque.getIdleObjects();
- for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
- final K k = entry.getKey();
- final ObjectDeque<T> deque = entry.getValue();
- if (deque != null) {
- if (getBlockWhenExhausted()) {
- result.put(k.toString(), Integer.valueOf(
- deque.getIdleObjects().getTakeQueueLength()));
+ if (isClosed() || maxIdle > -1 && maxIdle <= idleObjects.size()) {
+ try {
+ destroy(key, p, true, DestroyMode.NORMAL);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ } else {
+ if (getLifo()) {
+ idleObjects.addFirst(p);
} else {
- result.put(k.toString(), Integer.valueOf(0));
+ idleObjects.addLast(p);
+ }
+ if (isClosed()) {
+ // Pool closed while object was being added to idle objects.
+ // Make sure the returned object is destroyed rather than left
+ // in the idle object pool (which would effectively be a leak)
+ clear(key);
}
}
+ } finally {
+ if (hasBorrowWaiters()) {
+ reuseCapacity();
+ }
+ updateStatsReturn(activeTime);
}
- return result;
}
-
/**
- * Provides information on all the objects in the pool, both idle (waiting
- * to be borrowed) and active (currently borrowed).
- * <p>
- * Note: This is named listAllObjects so it is presented as an operation via
- * JMX. That means it won't be invoked unless the explicitly requested
- * whereas all attributes will be automatically requested when viewing the
- * attributes for an object in a tool like JConsole.
+ * Attempt to create one new instance to serve from the most heavily
+ * loaded pool that can add a new instance.
*
- * @return Information grouped by key on all the objects in the pool
+ * This method exists to ensure liveness in the pool when threads are
+ * parked waiting and capacity to create instances under the requested keys
+ * subsequently becomes available.
+ *
+ * This method is not guaranteed to create an instance and its selection
+ * of the most loaded pool that can create an instance may not always be
+ * correct, since it does not lock the pool and instances may be created,
+ * borrowed, returned or destroyed by other threads while it is executing.
*/
- @Override
- public Map<String,List<DefaultPooledObjectInfo>> listAllObjects() {
- final Map<String,List<DefaultPooledObjectInfo>> result =
- new HashMap<>();
+ private void reuseCapacity() {
+ final int maxTotalPerKeySave = getMaxTotalPerKey();
+ // Find the most loaded pool that could take a new instance
+ int maxQueueLength = 0;
+ LinkedBlockingDeque<PooledObject<T>> mostLoaded = null;
+ K loadedKey = null;
for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
final K k = entry.getKey();
final ObjectDeque<T> deque = entry.getValue();
if (deque != null) {
- final List<DefaultPooledObjectInfo> list =
- new ArrayList<>();
- result.put(k.toString(), list);
- for (final PooledObject<T> p : deque.getAllObjects().values()) {
- list.add(new DefaultPooledObjectInfo(p));
+ final LinkedBlockingDeque<PooledObject<T>> pool = deque.getIdleObjects();
+ final int queueLength = pool.getTakeQueueLength();
+ if (getNumActive(k) < maxTotalPerKeySave && queueLength > maxQueueLength) {
+ maxQueueLength = queueLength;
+ mostLoaded = pool;
+ loadedKey = k;
}
}
}
- return result;
- }
-
-
- //--- inner classes ----------------------------------------------
+ // Attempt to add an instance to the most loaded pool
+ if (mostLoaded != null) {
+ register(loadedKey);
+ try {
+ final PooledObject<T> p = create(loadedKey);
+ if (p != null) {
+ addIdleObject(loadedKey, p);
+ }
+ } catch (final Exception e) {
+ swallowException(e);
+ } finally {
+ deregister(loadedKey);
+ }
+ }
+ }
/**
- * Maintains information on the per key queue for a given key.
+ * Sets the configuration.
*
- * @param <S> type of objects in the pool
+ * @param conf the new configuration to use. This is used by value.
+ *
+ * @see GenericKeyedObjectPoolConfig
*/
- private class ObjectDeque<S> {
-
- private final LinkedBlockingDeque<PooledObject<S>> idleObjects;
-
- /*
- * Number of instances created - number destroyed.
- * Invariant: createCount <= maxTotalPerKey
- */
- private final AtomicInteger createCount = new AtomicInteger(0);
-
- private long makeObjectCount = 0;
- private final Object makeObjectCountLock = new Object();
-
- /*
- * The map is keyed on pooled instances, wrapped to ensure that
- * they work properly as keys.
- */
- private final Map<IdentityWrapper<S>, PooledObject<S>> allObjects =
- new ConcurrentHashMap<>();
-
- /*
- * Number of threads with registered interest in this key.
- * register(K) increments this counter and deRegister(K) decrements it.
- * Invariant: empty keyed pool will not be dropped unless numInterested
- * is 0.
- */
- private final AtomicLong numInterested = new AtomicLong(0);
-
- /**
- * Create a new ObjecDeque with the given fairness policy.
- * @param fairness true means client threads waiting to borrow / return instances
- * will be served as if waiting in a FIFO queue.
- */
- public ObjectDeque(final boolean fairness) {
- idleObjects = new LinkedBlockingDeque<>(fairness);
- }
-
- /**
- * Obtain the idle objects for the current key.
- *
- * @return The idle objects
- */
- public LinkedBlockingDeque<PooledObject<S>> getIdleObjects() {
- return idleObjects;
- }
-
- /**
- * Obtain the count of the number of objects created for the current
- * key.
- *
- * @return The number of objects created for this key
- */
- public AtomicInteger getCreateCount() {
- return createCount;
- }
-
- /**
- * Obtain the number of threads with an interest registered in this key.
- *
- * @return The number of threads with a registered interest in this key
- */
- public AtomicLong getNumInterested() {
- return numInterested;
- }
-
- /**
- * Obtain all the objects for the current key.
- *
- * @return All the objects
- */
- public Map<IdentityWrapper<S>, PooledObject<S>> getAllObjects() {
- return allObjects;
- }
-
- @Override
- public String toString() {
- final StringBuilder builder = new StringBuilder();
- builder.append("ObjectDeque [idleObjects=");
- builder.append(idleObjects);
- builder.append(", createCount=");
- builder.append(createCount);
- builder.append(", allObjects=");
- builder.append(allObjects);
- builder.append(", numInterested=");
- builder.append(numInterested);
- builder.append("]");
- return builder.toString();
- }
-
+ public void setConfig(final GenericKeyedObjectPoolConfig<T> conf) {
+ super.setConfig(conf);
+ setMaxIdlePerKey(conf.getMaxIdlePerKey());
+ setMaxTotalPerKey(conf.getMaxTotalPerKey());
+ setMaxTotal(conf.getMaxTotal());
+ setMinIdlePerKey(conf.getMinIdlePerKey());
}
-
- //--- configuration attributes ---------------------------------------------
- private volatile int maxIdlePerKey =
- GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY;
- private volatile int minIdlePerKey =
- GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY;
- private volatile int maxTotalPerKey =
- GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY;
- private final KeyedPooledObjectFactory<K, T> factory;
- private final boolean fairness;
-
-
- //--- internal attributes --------------------------------------------------
-
- /*
- * My hash of sub-pools (ObjectQueue). The list of keys <b>must</b> be kept
- * in step with {@link #poolKeyList} using {@link #keyLock} to ensure any
- * changes to the list of current keys is made in a thread-safe manner.
+ /**
+ * Sets the cap on the number of "idle" instances per key in the pool.
+ * If maxIdlePerKey is set too low on heavily loaded systems it is possible
+ * you will see objects being destroyed and almost immediately new objects
+ * being created. This is a result of the active threads momentarily
+ * returning objects faster than they are requesting them, causing the
+ * number of idle objects to rise above maxIdlePerKey. The best value for
+ * maxIdlePerKey for heavily loaded system will vary but the default is a
+ * good starting point.
+ *
+ * @param maxIdlePerKey the maximum number of "idle" instances that can be
+ * held in a given keyed sub-pool. Use a negative value
+ * for no limit
+ *
+ * @see #getMaxIdlePerKey
*/
- private final Map<K, ObjectDeque<T>> poolMap =
- new ConcurrentHashMap<>(); // @GuardedBy("keyLock") for write access (and some read access)
- /*
- * List of pool keys - used to control eviction order. The list of keys
- * <b>must</b> be kept in step with {@link #poolMap} using {@link #keyLock}
- * to ensure any changes to the list of current keys is made in a
- * thread-safe manner.
+ public void setMaxIdlePerKey(final int maxIdlePerKey) {
+ this.maxIdlePerKey = maxIdlePerKey;
+ }
+ /**
+ * Sets the limit on the number of object instances allocated by the pool
+ * (checked out or idle), per key. When the limit is reached, the sub-pool
+ * is said to be exhausted. A negative value indicates no limit.
+ *
+ * @param maxTotalPerKey the limit on the number of active instances per key
+ *
+ * @see #getMaxTotalPerKey
*/
- private final List<K> poolKeyList = new ArrayList<>(); // @GuardedBy("keyLock")
- private final ReadWriteLock keyLock = new ReentrantReadWriteLock(true);
- /*
- * The combined count of the currently active objects for all keys and those
- * in the process of being created. Under load, it may exceed
- * {@link #maxTotal} but there will never be more than {@link #maxTotal}
- * created at any one time.
+ public void setMaxTotalPerKey(final int maxTotalPerKey) {
+ this.maxTotalPerKey = maxTotalPerKey;
+ }
+ /**
+ * Sets the target for the minimum number of idle objects to maintain in
+ * each of the keyed sub-pools. This setting only has an effect if it is
+ * positive and {@link #getTimeBetweenEvictionRunsMillis()} is greater than
+ * zero. If this is the case, an attempt is made to ensure that each
+ * sub-pool has the required minimum number of instances during idle object
+ * eviction runs.
+ * <p>
+ * If the configured value of minIdlePerKey is greater than the configured
+ * value for maxIdlePerKey then the value of maxIdlePerKey will be used
+ * instead.
+ *
+ * @param minIdlePerKey The minimum size of the each keyed pool
+ *
+ * @see #getMinIdlePerKey
+ * @see #getMaxIdlePerKey()
+ * @see #setTimeBetweenEvictionRunsMillis
*/
- private final AtomicInteger numTotal = new AtomicInteger(0);
- private Iterator<K> evictionKeyIterator = null; // @GuardedBy("evictionLock")
- private K evictionKey = null; // @GuardedBy("evictionLock")
-
- // JMX specific attributes
- private static final String ONAME_BASE =
- "org.apache.commons.pool2:type=GenericKeyedObjectPool,name=";
+ public void setMinIdlePerKey(final int minIdlePerKey) {
+ this.minIdlePerKey = minIdlePerKey;
+ }
@Override
protected void toStringAppendFields(final StringBuilder builder) {
@@ -1645,4 +1630,19 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
builder.append(", evictionKey=");
builder.append(evictionKey);
}
+
+ /**
+ * Whether there is at least one thread waiting on this deque, add an pool object.
+ * @param key pool key.
+ * @param idleObjects list of idle pool objects.
+ */
+ private void whenWaitersAddObject(final K key, final LinkedBlockingDeque<PooledObject<T>> idleObjects) {
+ if (idleObjects.hasTakeWaiters()) {
+ try {
+ addObject(key);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ }
+ }
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java b/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java
index a22330b..827210a 100644
--- a/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java
+++ b/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java
@@ -69,30 +69,40 @@ public class GenericKeyedObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
public GenericKeyedObjectPoolConfig() {
}
+ @SuppressWarnings("unchecked")
+ @Override
+ public GenericKeyedObjectPoolConfig<T> clone() {
+ try {
+ return (GenericKeyedObjectPoolConfig<T>) super.clone();
+ } catch (final CloneNotSupportedException e) {
+ throw new AssertionError(); // Can't happen
+ }
+ }
+
/**
- * Get the value for the {@code maxTotal} configuration attribute
+ * Get the value for the {@code maxIdlePerKey} configuration attribute
* for pools created with this configuration instance.
*
- * @return The current setting of {@code maxTotal} for this
+ * @return The current setting of {@code maxIdlePerKey} for this
* configuration instance
*
- * @see GenericKeyedObjectPool#getMaxTotal()
+ * @see GenericKeyedObjectPool#getMaxIdlePerKey()
*/
- public int getMaxTotal() {
- return maxTotal;
+ public int getMaxIdlePerKey() {
+ return maxIdlePerKey;
}
/**
- * Set the value for the {@code maxTotal} configuration attribute for
- * pools created with this configuration instance.
+ * Get the value for the {@code maxTotal} configuration attribute
+ * for pools created with this configuration instance.
*
- * @param maxTotal The new setting of {@code maxTotal}
- * for this configuration instance
+ * @return The current setting of {@code maxTotal} for this
+ * configuration instance
*
- * @see GenericKeyedObjectPool#setMaxTotal(int)
+ * @see GenericKeyedObjectPool#getMaxTotal()
*/
- public void setMaxTotal(final int maxTotal) {
- this.maxTotal = maxTotal;
+ public int getMaxTotal() {
+ return maxTotal;
}
/**
@@ -109,19 +119,6 @@ public class GenericKeyedObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
}
/**
- * Set the value for the {@code maxTotalPerKey} configuration attribute for
- * pools created with this configuration instance.
- *
- * @param maxTotalPerKey The new setting of {@code maxTotalPerKey}
- * for this configuration instance
- *
- * @see GenericKeyedObjectPool#setMaxTotalPerKey(int)
- */
- public void setMaxTotalPerKey(final int maxTotalPerKey) {
- this.maxTotalPerKey = maxTotalPerKey;
- }
-
- /**
* Get the value for the {@code minIdlePerKey} configuration attribute
* for pools created with this configuration instance.
*
@@ -135,52 +132,55 @@ public class GenericKeyedObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
}
/**
- * Set the value for the {@code minIdlePerKey} configuration attribute for
+ * Set the value for the {@code maxIdlePerKey} configuration attribute for
* pools created with this configuration instance.
*
- * @param minIdlePerKey The new setting of {@code minIdlePerKey}
+ * @param maxIdlePerKey The new setting of {@code maxIdlePerKey}
* for this configuration instance
*
- * @see GenericKeyedObjectPool#setMinIdlePerKey(int)
+ * @see GenericKeyedObjectPool#setMaxIdlePerKey(int)
*/
- public void setMinIdlePerKey(final int minIdlePerKey) {
- this.minIdlePerKey = minIdlePerKey;
+ public void setMaxIdlePerKey(final int maxIdlePerKey) {
+ this.maxIdlePerKey = maxIdlePerKey;
}
/**
- * Get the value for the {@code maxIdlePerKey} configuration attribute
- * for pools created with this configuration instance.
+ * Set the value for the {@code maxTotal} configuration attribute for
+ * pools created with this configuration instance.
*
- * @return The current setting of {@code maxIdlePerKey} for this
- * configuration instance
+ * @param maxTotal The new setting of {@code maxTotal}
+ * for this configuration instance
*
- * @see GenericKeyedObjectPool#getMaxIdlePerKey()
+ * @see GenericKeyedObjectPool#setMaxTotal(int)
*/
- public int getMaxIdlePerKey() {
- return maxIdlePerKey;
+ public void setMaxTotal(final int maxTotal) {
+ this.maxTotal = maxTotal;
}
/**
- * Set the value for the {@code maxIdlePerKey} configuration attribute for
+ * Set the value for the {@code maxTotalPerKey} configuration attribute for
* pools created with this configuration instance.
*
- * @param maxIdlePerKey The new setting of {@code maxIdlePerKey}
+ * @param maxTotalPerKey The new setting of {@code maxTotalPerKey}
* for this configuration instance
*
- * @see GenericKeyedObjectPool#setMaxIdlePerKey(int)
+ * @see GenericKeyedObjectPool#setMaxTotalPerKey(int)
*/
- public void setMaxIdlePerKey(final int maxIdlePerKey) {
- this.maxIdlePerKey = maxIdlePerKey;
+ public void setMaxTotalPerKey(final int maxTotalPerKey) {
+ this.maxTotalPerKey = maxTotalPerKey;
}
- @SuppressWarnings("unchecked")
- @Override
- public GenericKeyedObjectPoolConfig<T> clone() {
- try {
- return (GenericKeyedObjectPoolConfig<T>) super.clone();
- } catch (final CloneNotSupportedException e) {
- throw new AssertionError(); // Can't happen
- }
+ /**
+ * Set the value for the {@code minIdlePerKey} configuration attribute for
+ * pools created with this configuration instance.
+ *
+ * @param minIdlePerKey The new setting of {@code minIdlePerKey}
+ * for this configuration instance
+ *
+ * @see GenericKeyedObjectPool#setMinIdlePerKey(int)
+ */
+ public void setMinIdlePerKey(final int minIdlePerKey) {
+ this.minIdlePerKey = minIdlePerKey;
}
@Override
diff --git a/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java b/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java
index 26c8590..1f48dfc 100644
--- a/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java
+++ b/src/main/java/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java
@@ -44,6 +44,42 @@ public interface GenericKeyedObjectPoolMXBean<K> {
boolean getBlockWhenExhausted();
/**
+ * See {@link GenericKeyedObjectPool#getBorrowedCount()}
+ * @return See {@link GenericKeyedObjectPool#getBorrowedCount()}
+ */
+ long getBorrowedCount();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getCreatedCount()}
+ * @return See {@link GenericKeyedObjectPool#getCreatedCount()}
+ */
+ long getCreatedCount();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getCreationStackTrace()}
+ * @return See {@link GenericKeyedObjectPool#getCreationStackTrace()}
+ */
+ String getCreationStackTrace();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getDestroyedByBorrowValidationCount()}
+ * @return See {@link GenericKeyedObjectPool#getDestroyedByBorrowValidationCount()}
+ */
+ long getDestroyedByBorrowValidationCount();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getDestroyedByEvictorCount()}
+ * @return See {@link GenericKeyedObjectPool#getDestroyedByEvictorCount()}
+ */
+ long getDestroyedByEvictorCount();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getDestroyedCount()}
+ * @return See {@link GenericKeyedObjectPool#getDestroyedCount()}
+ */
+ long getDestroyedCount();
+
+ /**
* See {@link GenericKeyedObjectPool#getFairness()}
* @return See {@link GenericKeyedObjectPool#getFairness()}
*/
@@ -56,6 +92,12 @@ public interface GenericKeyedObjectPoolMXBean<K> {
boolean getLifo();
/**
+ * See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}
+ * @return See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}
+ */
+ long getMaxBorrowWaitTimeMillis();
+
+ /**
* See {@link GenericKeyedObjectPool#getMaxIdlePerKey()}
* @return See {@link GenericKeyedObjectPool#getMaxIdlePerKey()}
*/
@@ -80,11 +122,31 @@ public interface GenericKeyedObjectPoolMXBean<K> {
long getMaxWaitMillis();
/**
+ * See {@link GenericKeyedObjectPool#getMeanActiveTimeMillis()}
+ * @return See {@link GenericKeyedObjectPool#getMeanActiveTimeMillis()}
+ */
+ long getMeanActiveTimeMillis();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}
+ * @return See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}
+ */
+ long getMeanBorrowWaitTimeMillis();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getMeanIdleTimeMillis()}
+ * @return See {@link GenericKeyedObjectPool#getMeanIdleTimeMillis()}
+ */
+ long getMeanIdleTimeMillis();
+
+ /**
* See {@link GenericKeyedObjectPool#getMinEvictableIdleTimeMillis()}
* @return See {@link GenericKeyedObjectPool#getMinEvictableIdleTimeMillis()}
*/
long getMinEvictableIdleTimeMillis();
+ // Expose getters for monitoring attributes
+
/**
* See {@link GenericKeyedObjectPool#getMinIdlePerKey()}
* @return See {@link GenericKeyedObjectPool#getMinIdlePerKey()}
@@ -98,6 +160,12 @@ public interface GenericKeyedObjectPoolMXBean<K> {
int getNumActive();
/**
+ * See {@link GenericKeyedObjectPool#getNumActivePerKey()}
+ * @return See {@link GenericKeyedObjectPool#getNumActivePerKey()}
+ */
+ Map<String,Integer> getNumActivePerKey();
+
+ /**
* See {@link GenericKeyedObjectPool#getNumIdle()}
* @return See {@link GenericKeyedObjectPool#getNumIdle()}
*/
@@ -110,11 +178,22 @@ public interface GenericKeyedObjectPoolMXBean<K> {
int getNumTestsPerEvictionRun();
/**
- * See {@link GenericKeyedObjectPool#getTestOnCreate()}
- * @return See {@link GenericKeyedObjectPool#getTestOnCreate()}
- * @since 2.2
+ * See {@link GenericKeyedObjectPool#getNumWaiters()}
+ * @return See {@link GenericKeyedObjectPool#getNumWaiters()}
*/
- boolean getTestOnCreate();
+ int getNumWaiters();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getNumWaitersByKey()}
+ * @return See {@link GenericKeyedObjectPool#getNumWaitersByKey()}
+ */
+ Map<String,Integer> getNumWaitersByKey();
+
+ /**
+ * See {@link GenericKeyedObjectPool#getReturnedCount()}
+ * @return See {@link GenericKeyedObjectPool#getReturnedCount()}
+ */
+ long getReturnedCount();
/**
* See {@link GenericKeyedObjectPool#getTestOnBorrow()}
@@ -123,6 +202,13 @@ public interface GenericKeyedObjectPoolMXBean<K> {
boolean getTestOnBorrow();
/**
+ * See {@link GenericKeyedObjectPool#getTestOnCreate()}
+ * @return See {@link GenericKeyedObjectPool#getTestOnCreate()}
+ * @since 2.2
+ */
+ boolean getTestOnCreate();
+
+ /**
* See {@link GenericKeyedObjectPool#getTestOnReturn()}
* @return See {@link GenericKeyedObjectPool#getTestOnReturn()}
*/
@@ -146,92 +232,6 @@ public interface GenericKeyedObjectPoolMXBean<K> {
*/
boolean isClosed();
- // Expose getters for monitoring attributes
-
- /**
- * See {@link GenericKeyedObjectPool#getNumActivePerKey()}
- * @return See {@link GenericKeyedObjectPool#getNumActivePerKey()}
- */
- Map<String,Integer> getNumActivePerKey();
-
- /**
- * See {@link GenericKeyedObjectPool#getBorrowedCount()}
- * @return See {@link GenericKeyedObjectPool#getBorrowedCount()}
- */
- long getBorrowedCount();
-
- /**
- * See {@link GenericKeyedObjectPool#getReturnedCount()}
- * @return See {@link GenericKeyedObjectPool#getReturnedCount()}
- */
- long getReturnedCount();
-
- /**
- * See {@link GenericKeyedObjectPool#getCreatedCount()}
- * @return See {@link GenericKeyedObjectPool#getCreatedCount()}
- */
- long getCreatedCount();
-
- /**
- * See {@link GenericKeyedObjectPool#getDestroyedCount()}
- * @return See {@link GenericKeyedObjectPool#getDestroyedCount()}
- */
- long getDestroyedCount();
-
- /**
- * See {@link GenericKeyedObjectPool#getDestroyedByEvictorCount()}
- * @return See {@link GenericKeyedObjectPool#getDestroyedByEvictorCount()}
- */
- long getDestroyedByEvictorCount();
-
- /**
- * See {@link GenericKeyedObjectPool#getDestroyedByBorrowValidationCount()}
- * @return See {@link GenericKeyedObjectPool#getDestroyedByBorrowValidationCount()}
- */
- long getDestroyedByBorrowValidationCount();
-
- /**
- * See {@link GenericKeyedObjectPool#getMeanActiveTimeMillis()}
- * @return See {@link GenericKeyedObjectPool#getMeanActiveTimeMillis()}
- */
- long getMeanActiveTimeMillis();
-
- /**
- * See {@link GenericKeyedObjectPool#getMeanIdleTimeMillis()}
- * @return See {@link GenericKeyedObjectPool#getMeanIdleTimeMillis()}
- */
- long getMeanIdleTimeMillis();
-
- /**
- * See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}
- * @return See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}
- */
- long getMeanBorrowWaitTimeMillis();
-
- /**
- * See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}
- * @return See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}
- */
- long getMaxBorrowWaitTimeMillis();
-
- /**
- * See {@link GenericKeyedObjectPool#getCreationStackTrace()}
- * @return See {@link GenericKeyedObjectPool#getCreationStackTrace()}
- */
- String getCreationStackTrace();
-
- /**
- * See {@link GenericKeyedObjectPool#getNumWaiters()}
- * @return See {@link GenericKeyedObjectPool#getNumWaiters()}
- */
- int getNumWaiters();
-
- /**
- * See {@link GenericKeyedObjectPool#getNumWaitersByKey()}
- * @return See {@link GenericKeyedObjectPool#getNumWaitersByKey()}
- */
- Map<String,Integer> getNumWaitersByKey();
-
/**
* See {@link GenericKeyedObjectPool#listAllObjects()}
* @return See {@link GenericKeyedObjectPool#listAllObjects()}
diff --git a/src/main/java/org/apache/commons/pool2/impl/GenericObjectPool.java b/src/main/java/org/apache/commons/pool2/impl/GenericObjectPool.java
index a0ec3e5..4bbcae1 100644
--- a/src/main/java/org/apache/commons/pool2/impl/GenericObjectPool.java
+++ b/src/main/java/org/apache/commons/pool2/impl/GenericObjectPool.java
@@ -86,6 +86,46 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
private static final Duration DEFAULT_REMOVE_ABANDONED_TIMEOUT = Duration.ofSeconds(Integer.MAX_VALUE);
+ // JMX specific attributes
+ private static final String ONAME_BASE =
+ "org.apache.commons.pool2:type=GenericObjectPool,name=";
+
+ private volatile String factoryType = null;
+
+ private volatile int maxIdle = GenericObjectPoolConfig.DEFAULT_MAX_IDLE;
+
+ private volatile int minIdle = GenericObjectPoolConfig.DEFAULT_MIN_IDLE;
+
+ private final PooledObjectFactory<T> factory;
+
+ /*
+ * All of the objects currently associated with this pool in any state. It
+ * excludes objects that have been destroyed. The size of
+ * {@link #allObjects} will always be less than or equal to {@link
+ * #_maxActive}. Map keys are pooled objects, values are the PooledObject
+ * wrappers used internally by the pool.
+ */
+ private final Map<IdentityWrapper<T>, PooledObject<T>> allObjects =
+ new ConcurrentHashMap<>();
+
+ /*
+ * The combined count of the currently created objects and those in the
+ * process of being created. Under load, it may exceed {@link #_maxActive}
+ * if multiple threads try and create a new object at the same time but
+ * {@link #create()} will ensure that there are never more than
+ * {@link #_maxActive} objects created at any one time.
+ */
+ private final AtomicLong createCount = new AtomicLong(0);
+
+ private long makeObjectCount;
+
+ private final Object makeObjectCountLock = new Object();
+
+ private final LinkedBlockingDeque<PooledObject<T>> idleObjects;
+
+ // Additional configuration properties for abandoned object tracking
+ private volatile AbandonedConfig abandonedConfig;
+
/**
* Creates a new {@code GenericObjectPool} using defaults from
* {@link GenericObjectPoolConfig}.
@@ -144,302 +184,119 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
/**
- * Gets the cap on the number of "idle" instances in the pool. If maxIdle
- * is set too low on heavily loaded systems it is possible you will see
- * objects being destroyed and almost immediately new objects being created.
- * This is a result of the active threads momentarily returning objects
- * faster than they are requesting them, causing the number of idle
- * objects to rise above maxIdle. The best value for maxIdle for heavily
- * loaded system will vary but the default is a good starting point.
+ * Adds the provided wrapped pooled object to the set of idle objects for
+ * this pool. The object must already be part of the pool. If {@code p}
+ * is null, this is a no-op (no exception, but no impact on the pool).
*
- * @return the maximum number of "idle" instances that can be held in the
- * pool or a negative value if there is no limit
+ * @param p The object to make idle
*
- * @see #setMaxIdle
+ * @throws Exception If the factory fails to passivate the object
*/
- @Override
- public int getMaxIdle() {
- return maxIdle;
+ private void addIdleObject(final PooledObject<T> p) throws Exception {
+ if (p != null) {
+ factory.passivateObject(p);
+ if (getLifo()) {
+ idleObjects.addFirst(p);
+ } else {
+ idleObjects.addLast(p);
+ }
+ }
}
/**
- * Sets the cap on the number of "idle" instances in the pool. If maxIdle
- * is set too low on heavily loaded systems it is possible you will see
- * objects being destroyed and almost immediately new objects being created.
- * This is a result of the active threads momentarily returning objects
- * faster than they are requesting them, causing the number of idle
- * objects to rise above maxIdle. The best value for maxIdle for heavily
- * loaded system will vary but the default is a good starting point.
- *
- * @param maxIdle
- * The cap on the number of "idle" instances in the pool. Use a
- * negative value to indicate an unlimited number of idle
- * instances
- *
- * @see #getMaxIdle
+ * Creates an object, and place it into the pool. addObject() is useful for
+ * "pre-loading" a pool with idle objects.
+ * <p>
+ * If there is no capacity available to add to the pool, this is a no-op
+ * (no exception, no impact to the pool). </p>
*/
- public void setMaxIdle(final int maxIdle) {
- this.maxIdle = maxIdle;
+ @Override
+ public void addObject() throws Exception {
+ assertOpen();
+ if (factory == null) {
+ throw new IllegalStateException(
+ "Cannot add objects without a factory.");
+ }
+ final PooledObject<T> p = create();
+ addIdleObject(p);
}
/**
- * Sets the target for the minimum number of idle objects to maintain in
- * the pool. This setting only has an effect if it is positive and
- * {@link #getTimeBetweenEvictionRunsMillis()} is greater than zero. If this
- * is the case, an attempt is made to ensure that the pool has the required
- * minimum number of instances during idle object eviction runs.
+ * Equivalent to <code>{@link #borrowObject(long)
+ * borrowObject}({@link #getMaxWaitMillis()})</code>.
* <p>
- * If the configured value of minIdle is greater than the configured value
- * for maxIdle then the value of maxIdle will be used instead.
+ * {@inheritDoc}
* </p>
- *
- * @param minIdle
- * The minimum number of objects.
- *
- * @see #getMinIdle()
- * @see #getMaxIdle()
- * @see #getTimeBetweenEvictionRunsMillis()
*/
- public void setMinIdle(final int minIdle) {
- this.minIdle = minIdle;
+ @Override
+ public T borrowObject() throws Exception {
+ return borrowObject(getMaxWaitMillis());
}
/**
- * Gets the target for the minimum number of idle objects to maintain in
- * the pool. This setting only has an effect if it is positive and
- * {@link #getTimeBetweenEvictionRunsMillis()} is greater than zero. If this
- * is the case, an attempt is made to ensure that the pool has the required
- * minimum number of instances during idle object eviction runs.
+ * Borrows an object from the pool using the specific waiting time which only
+ * applies if {@link #getBlockWhenExhausted()} is true.
* <p>
- * If the configured value of minIdle is greater than the configured value
- * for maxIdle then the value of maxIdle will be used instead.
+ * If there is one or more idle instance available in the pool, then an
+ * idle instance will be selected based on the value of {@link #getLifo()},
+ * activated and returned. If activation fails, or {@link #getTestOnBorrow()
+ * testOnBorrow} is set to {@code true} and validation fails, the
+ * instance is destroyed and the next available instance is examined. This
+ * continues until either a valid instance is returned or there are no more
+ * idle instances available.
+ * </p>
+ * <p>
+ * If there are no idle instances available in the pool, behavior depends on
+ * the {@link #getMaxTotal() maxTotal}, (if applicable)
+ * {@link #getBlockWhenExhausted()} and the value passed in to the
+ * {@code borrowMaxWaitMillis} parameter. If the number of instances
+ * checked out from the pool is less than {@code maxTotal,} a new
+ * instance is created, activated and (if applicable) validated and returned
+ * to the caller. If validation fails, a {@code NoSuchElementException}
+ * is thrown.
+ * </p>
+ * <p>
+ * If the pool is exhausted (no available idle instances and no capacity to
+ * create new ones), this method will either block (if
+ * {@link #getBlockWhenExhausted()} is true) or throw a
+ * {@code NoSuchElementException} (if
+ * {@link #getBlockWhenExhausted()} is false). The length of time that this
+ * method will block when {@link #getBlockWhenExhausted()} is true is
+ * determined by the value passed in to the {@code borrowMaxWaitMillis}
+ * parameter.
+ * </p>
+ * <p>
+ * When the pool is exhausted, multiple calling threads may be
+ * simultaneously blocked waiting for instances to become available. A
+ * "fairness" algorithm has been implemented to ensure that threads receive
+ * available instances in request arrival order.
* </p>
*
- * @return The minimum number of objects.
- *
- * @see #setMinIdle(int)
- * @see #setMaxIdle(int)
- * @see #setTimeBetweenEvictionRunsMillis(long)
- */
- @Override
- public int getMinIdle() {
- final int maxIdleSave = getMaxIdle();
- if (this.minIdle > maxIdleSave) {
- return maxIdleSave;
- }
- return minIdle;
- }
-
- /**
- * Gets whether or not abandoned object removal is configured for this pool.
+ * @param borrowMaxWaitMillis The time to wait in milliseconds for an object
+ * to become available
*
- * @return true if this pool is configured to detect and remove
- * abandoned objects
- */
- @Override
- public boolean isAbandonedConfig() {
- return abandonedConfig != null;
- }
-
- /**
- * Gets whether this pool identifies and logs any abandoned objects.
+ * @return object instance from the pool
*
- * @return {@code true} if abandoned object removal is configured for this
- * pool and removal events are to be logged otherwise {@code false}
+ * @throws NoSuchElementException if an instance cannot be returned
*
- * @see AbandonedConfig#getLogAbandoned()
+ * @throws Exception if an object instance cannot be returned due to an
+ * error
*/
- @Override
- public boolean getLogAbandoned() {
- final AbandonedConfig ac = this.abandonedConfig;
- return ac != null && ac.getLogAbandoned();
- }
+ public T borrowObject(final long borrowMaxWaitMillis) throws Exception {
+ assertOpen();
- /**
- * Gets whether a check is made for abandoned objects when an object is borrowed
- * from this pool.
- *
- * @return {@code true} if abandoned object removal is configured to be
- * activated by borrowObject otherwise {@code false}
- *
- * @see AbandonedConfig#getRemoveAbandonedOnBorrow()
- */
- @Override
- public boolean getRemoveAbandonedOnBorrow() {
final AbandonedConfig ac = this.abandonedConfig;
- return ac != null && ac.getRemoveAbandonedOnBorrow();
- }
+ if (ac != null && ac.getRemoveAbandonedOnBorrow() &&
+ (getNumIdle() < 2) &&
+ (getNumActive() > getMaxTotal() - 3) ) {
+ removeAbandoned(ac);
+ }
- /**
- * Gets whether a check is made for abandoned objects when the evictor runs.
- *
- * @return {@code true} if abandoned object removal is configured to be
- * activated when the evictor runs otherwise {@code false}
- *
- * @see AbandonedConfig#getRemoveAbandonedOnMaintenance()
- */
- @Override
- public boolean getRemoveAbandonedOnMaintenance() {
- final AbandonedConfig ac = this.abandonedConfig;
- return ac != null && ac.getRemoveAbandonedOnMaintenance();
- }
+ PooledObject<T> p = null;
- /**
- * Gets the timeout before which an object will be considered to be
- * abandoned by this pool.
- *
- * @return The abandoned object timeout in seconds if abandoned object
- * removal is configured for this pool; Integer.MAX_VALUE otherwise.
- *
- * @see AbandonedConfig#getRemoveAbandonedTimeout()
- * @see AbandonedConfig#getRemoveAbandonedTimeoutDuration()
- * @deprecated Use {@link #getRemoveAbandonedTimeoutDuration()}.
- */
- @Override
- @Deprecated
- public int getRemoveAbandonedTimeout() {
- final AbandonedConfig ac = this.abandonedConfig;
- return ac != null ? ac.getRemoveAbandonedTimeout() : Integer.MAX_VALUE;
- }
-
- /**
- * Gets the timeout before which an object will be considered to be
- * abandoned by this pool.
- *
- * @return The abandoned object timeout in seconds if abandoned object
- * removal is configured for this pool; Integer.MAX_VALUE otherwise.
- *
- * @see AbandonedConfig#getRemoveAbandonedTimeout()
- * @see AbandonedConfig#getRemoveAbandonedTimeoutDuration()
- */
- public Duration getRemoveAbandonedTimeoutDuration() {
- final AbandonedConfig ac = this.abandonedConfig;
- return ac != null ? ac.getRemoveAbandonedTimeoutDuration() : DEFAULT_REMOVE_ABANDONED_TIMEOUT;
- }
-
- /**
- * Sets the base pool configuration.
- *
- * @param conf the new configuration to use. This is used by value.
- *
- * @see GenericObjectPoolConfig
- */
- public void setConfig(final GenericObjectPoolConfig<T> conf) {
- super.setConfig(conf);
- setMaxIdle(conf.getMaxIdle());
- setMinIdle(conf.getMinIdle());
- setMaxTotal(conf.getMaxTotal());
- }
-
- /**
- * Sets the abandoned object removal configuration.
- *
- * @param abandonedConfig the new configuration to use. This is used by value.
- *
- * @see AbandonedConfig
- */
- @SuppressWarnings("resource") // PrintWriter is managed elsewhere
- public void setAbandonedConfig(final AbandonedConfig abandonedConfig) {
- if (abandonedConfig == null) {
- this.abandonedConfig = null;
- } else {
- this.abandonedConfig = new AbandonedConfig();
- this.abandonedConfig.setLogAbandoned(abandonedConfig.getLogAbandoned());
- this.abandonedConfig.setLogWriter(abandonedConfig.getLogWriter());
- this.abandonedConfig.setRemoveAbandonedOnBorrow(abandonedConfig.getRemoveAbandonedOnBorrow());
- this.abandonedConfig.setRemoveAbandonedOnMaintenance(abandonedConfig.getRemoveAbandonedOnMaintenance());
- this.abandonedConfig.setRemoveAbandonedTimeout(abandonedConfig.getRemoveAbandonedTimeoutDuration());
- this.abandonedConfig.setUseUsageTracking(abandonedConfig.getUseUsageTracking());
- this.abandonedConfig.setRequireFullStackTrace(abandonedConfig.getRequireFullStackTrace());
- }
- }
-
- /**
- * Obtains a reference to the factory used to create, destroy and validate
- * the objects used by this pool.
- *
- * @return the factory
- */
- public PooledObjectFactory<T> getFactory() {
- return factory;
- }
-
- /**
- * Equivalent to <code>{@link #borrowObject(long)
- * borrowObject}({@link #getMaxWaitMillis()})</code>.
- * <p>
- * {@inheritDoc}
- * </p>
- */
- @Override
- public T borrowObject() throws Exception {
- return borrowObject(getMaxWaitMillis());
- }
-
- /**
- * Borrows an object from the pool using the specific waiting time which only
- * applies if {@link #getBlockWhenExhausted()} is true.
- * <p>
- * If there is one or more idle instance available in the pool, then an
- * idle instance will be selected based on the value of {@link #getLifo()},
- * activated and returned. If activation fails, or {@link #getTestOnBorrow()
- * testOnBorrow} is set to {@code true} and validation fails, the
- * instance is destroyed and the next available instance is examined. This
- * continues until either a valid instance is returned or there are no more
- * idle instances available.
- * </p>
- * <p>
- * If there are no idle instances available in the pool, behavior depends on
- * the {@link #getMaxTotal() maxTotal}, (if applicable)
- * {@link #getBlockWhenExhausted()} and the value passed in to the
- * {@code borrowMaxWaitMillis} parameter. If the number of instances
- * checked out from the pool is less than {@code maxTotal,} a new
- * instance is created, activated and (if applicable) validated and returned
- * to the caller. If validation fails, a {@code NoSuchElementException}
- * is thrown.
- * </p>
- * <p>
- * If the pool is exhausted (no available idle instances and no capacity to
- * create new ones), this method will either block (if
- * {@link #getBlockWhenExhausted()} is true) or throw a
- * {@code NoSuchElementException} (if
- * {@link #getBlockWhenExhausted()} is false). The length of time that this
- * method will block when {@link #getBlockWhenExhausted()} is true is
- * determined by the value passed in to the {@code borrowMaxWaitMillis}
- * parameter.
- * </p>
- * <p>
- * When the pool is exhausted, multiple calling threads may be
- * simultaneously blocked waiting for instances to become available. A
- * "fairness" algorithm has been implemented to ensure that threads receive
- * available instances in request arrival order.
- * </p>
- *
- * @param borrowMaxWaitMillis The time to wait in milliseconds for an object
- * to become available
- *
- * @return object instance from the pool
- *
- * @throws NoSuchElementException if an instance cannot be returned
- *
- * @throws Exception if an object instance cannot be returned due to an
- * error
- */
- public T borrowObject(final long borrowMaxWaitMillis) throws Exception {
- assertOpen();
-
- final AbandonedConfig ac = this.abandonedConfig;
- if (ac != null && ac.getRemoveAbandonedOnBorrow() &&
- (getNumIdle() < 2) &&
- (getNumActive() > getMaxTotal() - 3) ) {
- removeAbandoned(ac);
- }
-
- PooledObject<T> p = null;
-
- // Get local copy of current config so it is consistent for entire
- // method execution
- final boolean blockWhenExhausted = getBlockWhenExhausted();
+ // Get local copy of current config so it is consistent for entire
+ // method execution
+ final boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
final long waitTimeMillis = System.currentTimeMillis();
@@ -526,199 +383,44 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
/**
- * {@inheritDoc}
- * <p>
- * If {@link #getMaxIdle() maxIdle} is set to a positive value and the
- * number of idle instances has reached this value, the returning instance
- * is destroyed.
- * </p>
- * <p>
- * If {@link #getTestOnReturn() testOnReturn} == true, the returning
- * instance is validated before being returned to the idle instance pool. In
- * this case, if validation fails, the instance is destroyed.
- * </p>
+ * Clears any objects sitting idle in the pool by removing them from the
+ * idle instance pool and then invoking the configured
+ * {@link PooledObjectFactory#destroyObject(PooledObject)} method on each
+ * idle instance.
* <p>
- * Exceptions encountered destroying objects for any reason are swallowed
- * but notified via a {@link SwallowedExceptionListener}.
+ * Implementation notes:
* </p>
+ * <ul>
+ * <li>This method does not destroy or effect in any way instances that are
+ * checked out of the pool when it is invoked.</li>
+ * <li>Invoking this method does not prevent objects being returned to the
+ * idle instance pool, even during its execution. Additional instances may
+ * be returned while removed items are being destroyed.</li>
+ * <li>Exceptions encountered destroying idle instances are swallowed
+ * but notified via a {@link SwallowedExceptionListener}.</li>
+ * </ul>
*/
@Override
- public void returnObject(final T obj) {
- final PooledObject<T> p = allObjects.get(new IdentityWrapper<>(obj));
-
- if (p == null) {
- if (!isAbandonedConfig()) {
- throw new IllegalStateException(
- "Returned object not currently part of this pool");
- }
- return; // Object was abandoned and removed
- }
-
- markReturningState(p);
-
- final long activeTime = p.getActiveTimeMillis();
-
- if (getTestOnReturn() && !factory.validateObject(p)) {
- try {
- destroy(p, DestroyMode.NORMAL);
- } catch (final Exception e) {
- swallowException(e);
- }
- try {
- ensureIdle(1, false);
- } catch (final Exception e) {
- swallowException(e);
- }
- updateStatsReturn(activeTime);
- return;
- }
-
- try {
- factory.passivateObject(p);
- } catch (final Exception e1) {
- swallowException(e1);
- try {
- destroy(p, DestroyMode.NORMAL);
- } catch (final Exception e) {
- swallowException(e);
- }
- try {
- ensureIdle(1, false);
- } catch (final Exception e) {
- swallowException(e);
- }
- updateStatsReturn(activeTime);
- return;
- }
-
- if (!p.deallocate()) {
- throw new IllegalStateException(
- "Object has already been returned to this pool or is invalid");
- }
+ public void clear() {
+ PooledObject<T> p = idleObjects.poll();
- final int maxIdleSave = getMaxIdle();
- if (isClosed() || maxIdleSave > -1 && maxIdleSave <= idleObjects.size()) {
+ while (p != null) {
try {
destroy(p, DestroyMode.NORMAL);
} catch (final Exception e) {
swallowException(e);
}
- try {
- ensureIdle(1, false);
- } catch (final Exception e) {
- swallowException(e);
- }
- } else {
- if (getLifo()) {
- idleObjects.addFirst(p);
- } else {
- idleObjects.addLast(p);
- }
- if (isClosed()) {
- // Pool closed while object was being added to idle objects.
- // Make sure the returned object is destroyed rather than left
- // in the idle object pool (which would effectively be a leak)
- clear();
- }
+ p = idleObjects.poll();
}
- updateStatsReturn(activeTime);
}
/**
- * {@inheritDoc}
+ * Closes the pool. Once the pool is closed, {@link #borrowObject()} will
+ * fail with IllegalStateException, but {@link #returnObject(Object)} and
+ * {@link #invalidateObject(Object)} will continue to work, with returned
+ * objects destroyed on return.
* <p>
- * Activation of this method decrements the active count and attempts to
- * destroy the instance, using the default (NORMAL) {@link DestroyMode}.
- * </p>
- *
- * @throws Exception if an exception occurs destroying the
- * object
- * @throws IllegalStateException if obj does not belong to this pool
- */
- @Override
- public void invalidateObject(final T obj) throws Exception {
- invalidateObject(obj, DestroyMode.NORMAL);
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Activation of this method decrements the active count and attempts to
- * destroy the instance, using the provided {@link DestroyMode}.
- * </p>
- *
- * @throws Exception if an exception occurs destroying the
- * object
- * @throws IllegalStateException if obj does not belong to this pool
- * @since 2.9.0
- */
- @Override
- public void invalidateObject(final T obj, final DestroyMode mode) throws Exception {
- final PooledObject<T> p = allObjects.get(new IdentityWrapper<>(obj));
- if (p == null) {
- if (isAbandonedConfig()) {
- return;
- }
- throw new IllegalStateException(
- "Invalidated object not currently part of this pool");
- }
- synchronized (p) {
- if (p.getState() != PooledObjectState.INVALID) {
- destroy(p, mode);
- }
- }
- ensureIdle(1, false);
- }
-
- /**
- * Clears any objects sitting idle in the pool by removing them from the
- * idle instance pool and then invoking the configured
- * {@link PooledObjectFactory#destroyObject(PooledObject)} method on each
- * idle instance.
- * <p>
- * Implementation notes:
- * </p>
- * <ul>
- * <li>This method does not destroy or effect in any way instances that are
- * checked out of the pool when it is invoked.</li>
- * <li>Invoking this method does not prevent objects being returned to the
- * idle instance pool, even during its execution. Additional instances may
- * be returned while removed items are being destroyed.</li>
- * <li>Exceptions encountered destroying idle instances are swallowed
- * but notified via a {@link SwallowedExceptionListener}.</li>
- * </ul>
- */
- @Override
- public void clear() {
- PooledObject<T> p = idleObjects.poll();
-
- while (p != null) {
- try {
- destroy(p, DestroyMode.NORMAL);
- } catch (final Exception e) {
- swallowException(e);
- }
- p = idleObjects.poll();
- }
- }
-
- @Override
- public int getNumActive() {
- return allObjects.size() - idleObjects.size();
- }
-
- @Override
- public int getNumIdle() {
- return idleObjects.size();
- }
-
- /**
- * Closes the pool. Once the pool is closed, {@link #borrowObject()} will
- * fail with IllegalStateException, but {@link #returnObject(Object)} and
- * {@link #invalidateObject(Object)} will continue to work, with returned
- * objects destroyed on return.
- * <p>
- * Destroys idle instances in the pool by invoking {@link #clear()}.
+ * Destroys idle instances in the pool by invoking {@link #clear()}.
* </p>
*/
@Override
@@ -748,127 +450,6 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
/**
- * {@inheritDoc}
- * <p>
- * Successive activations of this method examine objects in sequence,
- * cycling through objects in oldest-to-youngest order.
- * </p>
- */
- @Override
- public void evict() throws Exception {
- assertOpen();
-
- if (!idleObjects.isEmpty()) {
-
- PooledObject<T> underTest = null;
- final EvictionPolicy<T> evictionPolicy = getEvictionPolicy();
-
- synchronized (evictionLock) {
- final EvictionConfig evictionConfig = new EvictionConfig(
- getMinEvictableIdleTimeMillis(),
- getSoftMinEvictableIdleTimeMillis(),
- getMinIdle());
-
- final boolean testWhileIdle = getTestWhileIdle();
-
- for (int i = 0, m = getNumTests(); i < m; i++) {
- if (evictionIterator == null || !evictionIterator.hasNext()) {
- evictionIterator = new EvictionIterator(idleObjects);
- }
- if (!evictionIterator.hasNext()) {
- // Pool exhausted, nothing to do here
- return;
- }
-
- try {
- underTest = evictionIterator.next();
- } catch (final NoSuchElementException nsee) {
- // Object was borrowed in another thread
- // Don't count this as an eviction test so reduce i;
- i--;
- evictionIterator = null;
- continue;
- }
-
- if (!underTest.startEvictionTest()) {
- // Object was borrowed in another thread
- // Don't count this as an eviction test so reduce i;
- i--;
- continue;
- }
-
- // User provided eviction policy could throw all sorts of
- // crazy exceptions. Protect against such an exception
- // killing the eviction thread.
- boolean evict;
- try {
- evict = evictionPolicy.evict(evictionConfig, underTest,
- idleObjects.size());
- } catch (final Throwable t) {
- // Slightly convoluted as SwallowedExceptionListener
- // uses Exception rather than Throwable
- PoolUtils.checkRethrow(t);
- swallowException(new Exception(t));
- // Don't evict on error conditions
- evict = false;
- }
-
- if (evict) {
- destroy(underTest, DestroyMode.NORMAL);
- destroyedByEvictorCount.incrementAndGet();
- } else {
- if (testWhileIdle) {
- boolean active = false;
- try {
- factory.activateObject(underTest);
- active = true;
- } catch (final Exception e) {
- destroy(underTest, DestroyMode.NORMAL);
- destroyedByEvictorCount.incrementAndGet();
- }
- if (active) {
- if (!factory.validateObject(underTest)) {
- destroy(underTest, DestroyMode.NORMAL);
- destroyedByEvictorCount.incrementAndGet();
- } else {
- try {
- factory.passivateObject(underTest);
- } catch (final Exception e) {
- destroy(underTest, DestroyMode.NORMAL);
- destroyedByEvictorCount.incrementAndGet();
- }
- }
- }
- }
- if (!underTest.endEvictionTest(idleObjects)) {
- // TODO - May need to add code here once additional
- // states are used
- }
- }
- }
- }
- }
- final AbandonedConfig ac = this.abandonedConfig;
- if (ac != null && ac.getRemoveAbandonedOnMaintenance()) {
- removeAbandoned(ac);
- }
- }
-
- /**
- * Tries to ensure that {@link #getMinIdle()} idle instances are available
- * in the pool.
- *
- * @throws Exception If the associated factory throws an exception
- * @since 2.4
- */
- public void preparePool() throws Exception {
- if (getMinIdle() < 1) {
- return;
- }
- ensureMinIdle();
- }
-
- /**
* Attempts to create a new wrapped pooled object.
* <p>
* If there are {@link #getMaxTotal()} objects already in circulation
@@ -982,11 +563,6 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
}
- @Override
- void ensureMinIdle() throws Exception {
- ensureIdle(getMinIdle(), true);
- }
-
/**
* Tries to ensure that {@code idleCount} idle instances exist in the pool.
* <p>
@@ -1026,48 +602,223 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
}
+ @Override
+ void ensureMinIdle() throws Exception {
+ ensureIdle(getMinIdle(), true);
+ }
+
/**
- * Creates an object, and place it into the pool. addObject() is useful for
- * "pre-loading" a pool with idle objects.
+ * {@inheritDoc}
* <p>
- * If there is no capacity available to add to the pool, this is a no-op
- * (no exception, no impact to the pool). </p>
+ * Successive activations of this method examine objects in sequence,
+ * cycling through objects in oldest-to-youngest order.
+ * </p>
*/
@Override
- public void addObject() throws Exception {
+ public void evict() throws Exception {
assertOpen();
- if (factory == null) {
- throw new IllegalStateException(
- "Cannot add objects without a factory.");
- }
- final PooledObject<T> p = create();
- addIdleObject(p);
- }
- /**
- * Adds the provided wrapped pooled object to the set of idle objects for
- * this pool. The object must already be part of the pool. If {@code p}
- * is null, this is a no-op (no exception, but no impact on the pool).
- *
- * @param p The object to make idle
- *
- * @throws Exception If the factory fails to passivate the object
- */
- private void addIdleObject(final PooledObject<T> p) throws Exception {
- if (p != null) {
- factory.passivateObject(p);
- if (getLifo()) {
- idleObjects.addFirst(p);
- } else {
- idleObjects.addLast(p);
- }
- }
- }
+ if (!idleObjects.isEmpty()) {
- /**
- * Calculates the number of objects to test in a run of the idle object
- * evictor.
- *
+ PooledObject<T> underTest = null;
+ final EvictionPolicy<T> evictionPolicy = getEvictionPolicy();
+
+ synchronized (evictionLock) {
+ final EvictionConfig evictionConfig = new EvictionConfig(
+ getMinEvictableIdleTimeMillis(),
+ getSoftMinEvictableIdleTimeMillis(),
+ getMinIdle());
+
+ final boolean testWhileIdle = getTestWhileIdle();
+
+ for (int i = 0, m = getNumTests(); i < m; i++) {
+ if (evictionIterator == null || !evictionIterator.hasNext()) {
+ evictionIterator = new EvictionIterator(idleObjects);
+ }
+ if (!evictionIterator.hasNext()) {
+ // Pool exhausted, nothing to do here
+ return;
+ }
+
+ try {
+ underTest = evictionIterator.next();
+ } catch (final NoSuchElementException nsee) {
+ // Object was borrowed in another thread
+ // Don't count this as an eviction test so reduce i;
+ i--;
+ evictionIterator = null;
+ continue;
+ }
+
+ if (!underTest.startEvictionTest()) {
+ // Object was borrowed in another thread
+ // Don't count this as an eviction test so reduce i;
+ i--;
+ continue;
+ }
+
+ // User provided eviction policy could throw all sorts of
+ // crazy exceptions. Protect against such an exception
+ // killing the eviction thread.
+ boolean evict;
+ try {
+ evict = evictionPolicy.evict(evictionConfig, underTest,
+ idleObjects.size());
+ } catch (final Throwable t) {
+ // Slightly convoluted as SwallowedExceptionListener
+ // uses Exception rather than Throwable
+ PoolUtils.checkRethrow(t);
+ swallowException(new Exception(t));
+ // Don't evict on error conditions
+ evict = false;
+ }
+
+ if (evict) {
+ destroy(underTest, DestroyMode.NORMAL);
+ destroyedByEvictorCount.incrementAndGet();
+ } else {
+ if (testWhileIdle) {
+ boolean active = false;
+ try {
+ factory.activateObject(underTest);
+ active = true;
+ } catch (final Exception e) {
+ destroy(underTest, DestroyMode.NORMAL);
+ destroyedByEvictorCount.incrementAndGet();
+ }
+ if (active) {
+ if (!factory.validateObject(underTest)) {
+ destroy(underTest, DestroyMode.NORMAL);
+ destroyedByEvictorCount.incrementAndGet();
+ } else {
+ try {
+ factory.passivateObject(underTest);
+ } catch (final Exception e) {
+ destroy(underTest, DestroyMode.NORMAL);
+ destroyedByEvictorCount.incrementAndGet();
+ }
+ }
+ }
+ }
+ if (!underTest.endEvictionTest(idleObjects)) {
+ // TODO - May need to add code here once additional
+ // states are used
+ }
+ }
+ }
+ }
+ }
+ final AbandonedConfig ac = this.abandonedConfig;
+ if (ac != null && ac.getRemoveAbandonedOnMaintenance()) {
+ removeAbandoned(ac);
+ }
+ }
+
+ /**
+ * Obtains a reference to the factory used to create, destroy and validate
+ * the objects used by this pool.
+ *
+ * @return the factory
+ */
+ public PooledObjectFactory<T> getFactory() {
+ return factory;
+ }
+
+ /**
+ * Gets the type - including the specific type rather than the generic -
+ * of the factory.
+ *
+ * @return A string representation of the factory type
+ */
+ @Override
+ public String getFactoryType() {
+ // Not thread safe. Accept that there may be multiple evaluations.
+ if (factoryType == null) {
+ final StringBuilder result = new StringBuilder();
+ result.append(factory.getClass().getName());
+ result.append('<');
+ final Class<?> pooledObjectType =
+ PoolImplUtils.getFactoryType(factory.getClass());
+ result.append(pooledObjectType.getName());
+ result.append('>');
+ factoryType = result.toString();
+ }
+ return factoryType;
+ }
+
+ /**
+ * Gets whether this pool identifies and logs any abandoned objects.
+ *
+ * @return {@code true} if abandoned object removal is configured for this
+ * pool and removal events are to be logged otherwise {@code false}
+ *
+ * @see AbandonedConfig#getLogAbandoned()
+ */
+ @Override
+ public boolean getLogAbandoned() {
+ final AbandonedConfig ac = this.abandonedConfig;
+ return ac != null && ac.getLogAbandoned();
+ }
+
+ /**
+ * Gets the cap on the number of "idle" instances in the pool. If maxIdle
+ * is set too low on heavily loaded systems it is possible you will see
+ * objects being destroyed and almost immediately new objects being created.
+ * This is a result of the active threads momentarily returning objects
+ * faster than they are requesting them, causing the number of idle
+ * objects to rise above maxIdle. The best value for maxIdle for heavily
+ * loaded system will vary but the default is a good starting point.
+ *
+ * @return the maximum number of "idle" instances that can be held in the
+ * pool or a negative value if there is no limit
+ *
+ * @see #setMaxIdle
+ */
+ @Override
+ public int getMaxIdle() {
+ return maxIdle;
+ }
+
+ /**
+ * Gets the target for the minimum number of idle objects to maintain in
+ * the pool. This setting only has an effect if it is positive and
+ * {@link #getTimeBetweenEvictionRunsMillis()} is greater than zero. If this
+ * is the case, an attempt is made to ensure that the pool has the required
+ * minimum number of instances during idle object eviction runs.
+ * <p>
+ * If the configured value of minIdle is greater than the configured value
+ * for maxIdle then the value of maxIdle will be used instead.
+ * </p>
+ *
+ * @return The minimum number of objects.
+ *
+ * @see #setMinIdle(int)
+ * @see #setMaxIdle(int)
+ * @see #setTimeBetweenEvictionRunsMillis(long)
+ */
+ @Override
+ public int getMinIdle() {
+ final int maxIdleSave = getMaxIdle();
+ if (this.minIdle > maxIdleSave) {
+ return maxIdleSave;
+ }
+ return minIdle;
+ }
+
+ @Override
+ public int getNumActive() {
+ return allObjects.size() - idleObjects.size();
+ }
+
+ @Override
+ public int getNumIdle() {
+ return idleObjects.size();
+ }
+
+ /**
+ * Calculates the number of objects to test in a run of the idle object
+ * evictor.
+ *
* @return The number of objects to test for validity
*/
private int getNumTests() {
@@ -1080,6 +831,186 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
/**
+ * Gets an estimate of the number of threads currently blocked waiting for
+ * an object from the pool. This is intended for monitoring only, not for
+ * synchronization control.
+ *
+ * @return The estimate of the number of threads currently blocked waiting
+ * for an object from the pool
+ */
+ @Override
+ public int getNumWaiters() {
+ if (getBlockWhenExhausted()) {
+ return idleObjects.getTakeQueueLength();
+ }
+ return 0;
+ }
+
+ /**
+ * Gets whether a check is made for abandoned objects when an object is borrowed
+ * from this pool.
+ *
+ * @return {@code true} if abandoned object removal is configured to be
+ * activated by borrowObject otherwise {@code false}
+ *
+ * @see AbandonedConfig#getRemoveAbandonedOnBorrow()
+ */
+ @Override
+ public boolean getRemoveAbandonedOnBorrow() {
+ final AbandonedConfig ac = this.abandonedConfig;
+ return ac != null && ac.getRemoveAbandonedOnBorrow();
+ }
+
+
+ //--- Usage tracking support -----------------------------------------------
+
+ /**
+ * Gets whether a check is made for abandoned objects when the evictor runs.
+ *
+ * @return {@code true} if abandoned object removal is configured to be
+ * activated when the evictor runs otherwise {@code false}
+ *
+ * @see AbandonedConfig#getRemoveAbandonedOnMaintenance()
+ */
+ @Override
+ public boolean getRemoveAbandonedOnMaintenance() {
+ final AbandonedConfig ac = this.abandonedConfig;
+ return ac != null && ac.getRemoveAbandonedOnMaintenance();
+ }
+
+
+ //--- JMX support ----------------------------------------------------------
+
+ /**
+ * Gets the timeout before which an object will be considered to be
+ * abandoned by this pool.
+ *
+ * @return The abandoned object timeout in seconds if abandoned object
+ * removal is configured for this pool; Integer.MAX_VALUE otherwise.
+ *
+ * @see AbandonedConfig#getRemoveAbandonedTimeout()
+ * @see AbandonedConfig#getRemoveAbandonedTimeoutDuration()
+ * @deprecated Use {@link #getRemoveAbandonedTimeoutDuration()}.
+ */
+ @Override
+ @Deprecated
+ public int getRemoveAbandonedTimeout() {
+ final AbandonedConfig ac = this.abandonedConfig;
+ return ac != null ? ac.getRemoveAbandonedTimeout() : Integer.MAX_VALUE;
+ }
+
+ /**
+ * Gets the timeout before which an object will be considered to be
+ * abandoned by this pool.
+ *
+ * @return The abandoned object timeout in seconds if abandoned object
+ * removal is configured for this pool; Integer.MAX_VALUE otherwise.
+ *
+ * @see AbandonedConfig#getRemoveAbandonedTimeout()
+ * @see AbandonedConfig#getRemoveAbandonedTimeoutDuration()
+ */
+ public Duration getRemoveAbandonedTimeoutDuration() {
+ final AbandonedConfig ac = this.abandonedConfig;
+ return ac != null ? ac.getRemoveAbandonedTimeoutDuration() : DEFAULT_REMOVE_ABANDONED_TIMEOUT;
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * Activation of this method decrements the active count and attempts to
+ * destroy the instance, using the default (NORMAL) {@link DestroyMode}.
+ * </p>
+ *
+ * @throws Exception if an exception occurs destroying the
+ * object
+ * @throws IllegalStateException if obj does not belong to this pool
+ */
+ @Override
+ public void invalidateObject(final T obj) throws Exception {
+ invalidateObject(obj, DestroyMode.NORMAL);
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * Activation of this method decrements the active count and attempts to
+ * destroy the instance, using the provided {@link DestroyMode}.
+ * </p>
+ *
+ * @throws Exception if an exception occurs destroying the
+ * object
+ * @throws IllegalStateException if obj does not belong to this pool
+ * @since 2.9.0
+ */
+ @Override
+ public void invalidateObject(final T obj, final DestroyMode mode) throws Exception {
+ final PooledObject<T> p = allObjects.get(new IdentityWrapper<>(obj));
+ if (p == null) {
+ if (isAbandonedConfig()) {
+ return;
+ }
+ throw new IllegalStateException(
+ "Invalidated object not currently part of this pool");
+ }
+ synchronized (p) {
+ if (p.getState() != PooledObjectState.INVALID) {
+ destroy(p, mode);
+ }
+ }
+ ensureIdle(1, false);
+ }
+
+ // --- configuration attributes --------------------------------------------
+
+ /**
+ * Gets whether or not abandoned object removal is configured for this pool.
+ *
+ * @return true if this pool is configured to detect and remove
+ * abandoned objects
+ */
+ @Override
+ public boolean isAbandonedConfig() {
+ return abandonedConfig != null;
+ }
+ /**
+ * Provides information on all the objects in the pool, both idle (waiting
+ * to be borrowed) and active (currently borrowed).
+ * <p>
+ * Note: This is named listAllObjects so it is presented as an operation via
+ * JMX. That means it won't be invoked unless the explicitly requested
+ * whereas all attributes will be automatically requested when viewing the
+ * attributes for an object in a tool like JConsole.
+ * </p>
+ *
+ * @return Information grouped on all the objects in the pool
+ */
+ @Override
+ public Set<DefaultPooledObjectInfo> listAllObjects() {
+ final Set<DefaultPooledObjectInfo> result =
+ new HashSet<>(allObjects.size());
+ for (final PooledObject<T> p : allObjects.values()) {
+ result.add(new DefaultPooledObjectInfo(p));
+ }
+ return result;
+ }
+ /**
+ * Tries to ensure that {@link #getMinIdle()} idle instances are available
+ * in the pool.
+ *
+ * @throws Exception If the associated factory throws an exception
+ * @since 2.4
+ */
+ public void preparePool() throws Exception {
+ if (getMinIdle() < 1) {
+ return;
+ }
+ ensureMinIdle();
+ }
+
+
+ // --- internal attributes -------------------------------------------------
+
+ /**
* Recovers abandoned objects which have been checked out but
* not used since longer than the removeAbandonedTimeout.
*
@@ -1118,121 +1049,181 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
}
}
+ /**
+ * {@inheritDoc}
+ * <p>
+ * If {@link #getMaxIdle() maxIdle} is set to a positive value and the
+ * number of idle instances has reached this value, the returning instance
+ * is destroyed.
+ * </p>
+ * <p>
+ * If {@link #getTestOnReturn() testOnReturn} == true, the returning
+ * instance is validated before being returned to the idle instance pool. In
+ * this case, if validation fails, the instance is destroyed.
+ * </p>
+ * <p>
+ * Exceptions encountered destroying objects for any reason are swallowed
+ * but notified via a {@link SwallowedExceptionListener}.
+ * </p>
+ */
+ @Override
+ public void returnObject(final T obj) {
+ final PooledObject<T> p = allObjects.get(new IdentityWrapper<>(obj));
+
+ if (p == null) {
+ if (!isAbandonedConfig()) {
+ throw new IllegalStateException(
+ "Returned object not currently part of this pool");
+ }
+ return; // Object was abandoned and removed
+ }
+ markReturningState(p);
- //--- Usage tracking support -----------------------------------------------
+ final long activeTime = p.getActiveTimeMillis();
- @Override
- public void use(final T pooledObject) {
- final AbandonedConfig abandonedCfg = this.abandonedConfig;
- if (abandonedCfg != null && abandonedCfg.getUseUsageTracking()) {
- final PooledObject<T> wrapper = allObjects.get(new IdentityWrapper<>(pooledObject));
- wrapper.use();
+ if (getTestOnReturn() && !factory.validateObject(p)) {
+ try {
+ destroy(p, DestroyMode.NORMAL);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ try {
+ ensureIdle(1, false);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ updateStatsReturn(activeTime);
+ return;
}
- }
+ try {
+ factory.passivateObject(p);
+ } catch (final Exception e1) {
+ swallowException(e1);
+ try {
+ destroy(p, DestroyMode.NORMAL);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ try {
+ ensureIdle(1, false);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ updateStatsReturn(activeTime);
+ return;
+ }
- //--- JMX support ----------------------------------------------------------
-
- private volatile String factoryType = null;
+ if (!p.deallocate()) {
+ throw new IllegalStateException(
+ "Object has already been returned to this pool or is invalid");
+ }
+ final int maxIdleSave = getMaxIdle();
+ if (isClosed() || maxIdleSave > -1 && maxIdleSave <= idleObjects.size()) {
+ try {
+ destroy(p, DestroyMode.NORMAL);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ try {
+ ensureIdle(1, false);
+ } catch (final Exception e) {
+ swallowException(e);
+ }
+ } else {
+ if (getLifo()) {
+ idleObjects.addFirst(p);
+ } else {
+ idleObjects.addLast(p);
+ }
+ if (isClosed()) {
+ // Pool closed while object was being added to idle objects.
+ // Make sure the returned object is destroyed rather than left
+ // in the idle object pool (which would effectively be a leak)
+ clear();
+ }
+ }
+ updateStatsReturn(activeTime);
+ }
/**
- * Gets an estimate of the number of threads currently blocked waiting for
- * an object from the pool. This is intended for monitoring only, not for
- * synchronization control.
+ * Sets the abandoned object removal configuration.
*
- * @return The estimate of the number of threads currently blocked waiting
- * for an object from the pool
+ * @param abandonedConfig the new configuration to use. This is used by value.
+ *
+ * @see AbandonedConfig
*/
- @Override
- public int getNumWaiters() {
- if (getBlockWhenExhausted()) {
- return idleObjects.getTakeQueueLength();
+ @SuppressWarnings("resource") // PrintWriter is managed elsewhere
+ public void setAbandonedConfig(final AbandonedConfig abandonedConfig) {
+ if (abandonedConfig == null) {
+ this.abandonedConfig = null;
+ } else {
+ this.abandonedConfig = new AbandonedConfig();
+ this.abandonedConfig.setLogAbandoned(abandonedConfig.getLogAbandoned());
+ this.abandonedConfig.setLogWriter(abandonedConfig.getLogWriter());
+ this.abandonedConfig.setRemoveAbandonedOnBorrow(abandonedConfig.getRemoveAbandonedOnBorrow());
+ this.abandonedConfig.setRemoveAbandonedOnMaintenance(abandonedConfig.getRemoveAbandonedOnMaintenance());
+ this.abandonedConfig.setRemoveAbandonedTimeout(abandonedConfig.getRemoveAbandonedTimeoutDuration());
+ this.abandonedConfig.setUseUsageTracking(abandonedConfig.getUseUsageTracking());
+ this.abandonedConfig.setRequireFullStackTrace(abandonedConfig.getRequireFullStackTrace());
}
- return 0;
}
-
/**
- * Gets the type - including the specific type rather than the generic -
- * of the factory.
+ * Sets the base pool configuration.
*
- * @return A string representation of the factory type
+ * @param conf the new configuration to use. This is used by value.
+ *
+ * @see GenericObjectPoolConfig
*/
- @Override
- public String getFactoryType() {
- // Not thread safe. Accept that there may be multiple evaluations.
- if (factoryType == null) {
- final StringBuilder result = new StringBuilder();
- result.append(factory.getClass().getName());
- result.append('<');
- final Class<?> pooledObjectType =
- PoolImplUtils.getFactoryType(factory.getClass());
- result.append(pooledObjectType.getName());
- result.append('>');
- factoryType = result.toString();
- }
- return factoryType;
+ public void setConfig(final GenericObjectPoolConfig<T> conf) {
+ super.setConfig(conf);
+ setMaxIdle(conf.getMaxIdle());
+ setMinIdle(conf.getMinIdle());
+ setMaxTotal(conf.getMaxTotal());
+ }
+ /**
+ * Sets the cap on the number of "idle" instances in the pool. If maxIdle
+ * is set too low on heavily loaded systems it is possible you will see
+ * objects being destroyed and almost immediately new objects being created.
+ * This is a result of the active threads momentarily returning objects
+ * faster than they are requesting them, causing the number of idle
+ * objects to rise above maxIdle. The best value for maxIdle for heavily
+ * loaded system will vary but the default is a good starting point.
+ *
+ * @param maxIdle
+ * The cap on the number of "idle" instances in the pool. Use a
+ * negative value to indicate an unlimited number of idle
+ * instances
+ *
+ * @see #getMaxIdle
+ */
+ public void setMaxIdle(final int maxIdle) {
+ this.maxIdle = maxIdle;
}
/**
- * Provides information on all the objects in the pool, both idle (waiting
- * to be borrowed) and active (currently borrowed).
+ * Sets the target for the minimum number of idle objects to maintain in
+ * the pool. This setting only has an effect if it is positive and
+ * {@link #getTimeBetweenEvictionRunsMillis()} is greater than zero. If this
+ * is the case, an attempt is made to ensure that the pool has the required
+ * minimum number of instances during idle object eviction runs.
* <p>
- * Note: This is named listAllObjects so it is presented as an operation via
- * JMX. That means it won't be invoked unless the explicitly requested
- * whereas all attributes will be automatically requested when viewing the
- * attributes for an object in a tool like JConsole.
+ * If the configured value of minIdle is greater than the configured value
+ * for maxIdle then the value of maxIdle will be used instead.
* </p>
*
- * @return Information grouped on all the objects in the pool
+ * @param minIdle
+ * The minimum number of objects.
+ *
+ * @see #getMinIdle()
+ * @see #getMaxIdle()
+ * @see #getTimeBetweenEvictionRunsMillis()
*/
- @Override
- public Set<DefaultPooledObjectInfo> listAllObjects() {
- final Set<DefaultPooledObjectInfo> result =
- new HashSet<>(allObjects.size());
- for (final PooledObject<T> p : allObjects.values()) {
- result.add(new DefaultPooledObjectInfo(p));
- }
- return result;
+ public void setMinIdle(final int minIdle) {
+ this.minIdle = minIdle;
}
- // --- configuration attributes --------------------------------------------
-
- private volatile int maxIdle = GenericObjectPoolConfig.DEFAULT_MAX_IDLE;
- private volatile int minIdle = GenericObjectPoolConfig.DEFAULT_MIN_IDLE;
- private final PooledObjectFactory<T> factory;
-
-
- // --- internal attributes -------------------------------------------------
-
- /*
- * All of the objects currently associated with this pool in any state. It
- * excludes objects that have been destroyed. The size of
- * {@link #allObjects} will always be less than or equal to {@link
- * #_maxActive}. Map keys are pooled objects, values are the PooledObject
- * wrappers used internally by the pool.
- */
- private final Map<IdentityWrapper<T>, PooledObject<T>> allObjects =
- new ConcurrentHashMap<>();
- /*
- * The combined count of the currently created objects and those in the
- * process of being created. Under load, it may exceed {@link #_maxActive}
- * if multiple threads try and create a new object at the same time but
- * {@link #create()} will ensure that there are never more than
- * {@link #_maxActive} objects created at any one time.
- */
- private final AtomicLong createCount = new AtomicLong(0);
- private long makeObjectCount;
- private final Object makeObjectCountLock = new Object();
- private final LinkedBlockingDeque<PooledObject<T>> idleObjects;
-
- // JMX specific attributes
- private static final String ONAME_BASE =
- "org.apache.commons.pool2:type=GenericObjectPool,name=";
-
- // Additional configuration properties for abandoned object tracking
- private volatile AbandonedConfig abandonedConfig;
-
@Override
protected void toStringAppendFields(final StringBuilder builder) {
super.toStringAppendFields(builder);
@@ -1254,4 +1245,13 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
builder.append(abandonedConfig);
}
+ @Override
+ public void use(final T pooledObject) {
+ final AbandonedConfig abandonedCfg = this.abandonedConfig;
+ if (abandonedCfg != null && abandonedCfg.getUseUsageTracking()) {
+ final PooledObject<T> wrapper = allObjects.get(new IdentityWrapper<>(pooledObject));
+ wrapper.use();
+ }
+ }
+
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java b/src/main/java/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java
index c046795..de89c23 100644
--- a/src/main/java/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java
+++ b/src/main/java/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java
@@ -55,46 +55,57 @@ public class GenericObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
private int minIdle = DEFAULT_MIN_IDLE;
+ @SuppressWarnings("unchecked")
+ @Override
+ public GenericObjectPoolConfig<T> clone() {
+ try {
+ return (GenericObjectPoolConfig<T>) super.clone();
+ } catch (final CloneNotSupportedException e) {
+ throw new AssertionError(); // Can't happen
+ }
+ }
+
/**
- * Get the value for the {@code maxTotal} configuration attribute
+ * Get the value for the {@code maxIdle} configuration attribute
* for pools created with this configuration instance.
*
- * @return The current setting of {@code maxTotal} for this
+ * @return The current setting of {@code maxIdle} for this
* configuration instance
*
- * @see GenericObjectPool#getMaxTotal()
+ * @see GenericObjectPool#getMaxIdle()
*/
- public int getMaxTotal() {
- return maxTotal;
+ public int getMaxIdle() {
+ return maxIdle;
}
+
/**
- * Set the value for the {@code maxTotal} configuration attribute for
- * pools created with this configuration instance.
+ * Get the value for the {@code maxTotal} configuration attribute
+ * for pools created with this configuration instance.
*
- * @param maxTotal The new setting of {@code maxTotal}
- * for this configuration instance
+ * @return The current setting of {@code maxTotal} for this
+ * configuration instance
*
- * @see GenericObjectPool#setMaxTotal(int)
+ * @see GenericObjectPool#getMaxTotal()
*/
- public void setMaxTotal(final int maxTotal) {
- this.maxTotal = maxTotal;
+ public int getMaxTotal() {
+ return maxTotal;
}
-
/**
- * Get the value for the {@code maxIdle} configuration attribute
+ * Get the value for the {@code minIdle} configuration attribute
* for pools created with this configuration instance.
*
- * @return The current setting of {@code maxIdle} for this
+ * @return The current setting of {@code minIdle} for this
* configuration instance
*
- * @see GenericObjectPool#getMaxIdle()
+ * @see GenericObjectPool#getMinIdle()
*/
- public int getMaxIdle() {
- return maxIdle;
+ public int getMinIdle() {
+ return minIdle;
}
+
/**
* Set the value for the {@code maxIdle} configuration attribute for
* pools created with this configuration instance.
@@ -108,18 +119,17 @@ public class GenericObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
this.maxIdle = maxIdle;
}
-
/**
- * Get the value for the {@code minIdle} configuration attribute
- * for pools created with this configuration instance.
+ * Set the value for the {@code maxTotal} configuration attribute for
+ * pools created with this configuration instance.
*
- * @return The current setting of {@code minIdle} for this
- * configuration instance
+ * @param maxTotal The new setting of {@code maxTotal}
+ * for this configuration instance
*
- * @see GenericObjectPool#getMinIdle()
+ * @see GenericObjectPool#setMaxTotal(int)
*/
- public int getMinIdle() {
- return minIdle;
+ public void setMaxTotal(final int maxTotal) {
+ this.maxTotal = maxTotal;
}
/**
@@ -135,16 +145,6 @@ public class GenericObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
this.minIdle = minIdle;
}
- @SuppressWarnings("unchecked")
- @Override
- public GenericObjectPoolConfig<T> clone() {
- try {
- return (GenericObjectPoolConfig<T>) super.clone();
- } catch (final CloneNotSupportedException e) {
- throw new AssertionError(); // Can't happen
- }
- }
-
@Override
protected void toStringAppendFields(final StringBuilder builder) {
super.toStringAppendFields(builder);
diff --git a/src/main/java/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java b/src/main/java/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java
index 737ea54..1c3129e 100644
--- a/src/main/java/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java
+++ b/src/main/java/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java
@@ -41,213 +41,213 @@ public interface GenericObjectPoolMXBean {
boolean getBlockWhenExhausted();
/**
- * See {@link GenericObjectPool#getLifo()}
- * @return See {@link GenericObjectPool#getLifo()}
+ * See {@link GenericObjectPool#getBorrowedCount()}
+ * @return See {@link GenericObjectPool#getBorrowedCount()}
*/
- boolean getFairness();
+ long getBorrowedCount();
/**
- * See {@link GenericObjectPool#getFairness()}
- * @return See {@link GenericObjectPool#getFairness()}
+ * See {@link GenericObjectPool#getCreatedCount()}
+ * @return See {@link GenericObjectPool#getCreatedCount()}
*/
- boolean getLifo();
+ long getCreatedCount();
/**
- * See {@link GenericObjectPool#getMaxIdle()}
- * @return See {@link GenericObjectPool#getMaxIdle()}
+ * See {@link GenericObjectPool#getCreationStackTrace()}
+ * @return See {@link GenericObjectPool#getCreationStackTrace()}
*/
- int getMaxIdle();
+ String getCreationStackTrace();
/**
- * See {@link GenericObjectPool#getMaxTotal()}
- * @return See {@link GenericObjectPool#getMaxTotal()}
+ * See {@link GenericObjectPool#getDestroyedByBorrowValidationCount()}
+ * @return See {@link GenericObjectPool#getDestroyedByBorrowValidationCount()}
*/
- int getMaxTotal();
+ long getDestroyedByBorrowValidationCount();
/**
- * See {@link GenericObjectPool#getMaxWaitMillis()}
- * @return See {@link GenericObjectPool#getMaxWaitMillis()}
+ * See {@link GenericObjectPool#getDestroyedByEvictorCount()}
+ * @return See {@link GenericObjectPool#getDestroyedByEvictorCount()}
*/
- long getMaxWaitMillis();
+ long getDestroyedByEvictorCount();
/**
- * See {@link GenericObjectPool#getMinEvictableIdleTimeMillis()}
- * @return See {@link GenericObjectPool#getMinEvictableIdleTimeMillis()}
+ * See {@link GenericObjectPool#getDestroyedCount()}
+ * @return See {@link GenericObjectPool#getDestroyedCount()}
*/
- long getMinEvictableIdleTimeMillis();
+ long getDestroyedCount();
/**
- * See {@link GenericObjectPool#getMinIdle()}
- * @return See {@link GenericObjectPool#getMinIdle()}
+ * See {@link GenericObjectPool#getFactoryType()}
+ * @return See {@link GenericObjectPool#getFactoryType()}
*/
- int getMinIdle();
+ String getFactoryType();
/**
- * See {@link GenericObjectPool#getNumActive()}
- * @return See {@link GenericObjectPool#getNumActive()}
+ * See {@link GenericObjectPool#getLifo()}
+ * @return See {@link GenericObjectPool#getLifo()}
*/
- int getNumActive();
+ boolean getFairness();
/**
- * See {@link GenericObjectPool#getNumIdle()}
- * @return See {@link GenericObjectPool#getNumIdle()}
+ * See {@link GenericObjectPool#getFairness()}
+ * @return See {@link GenericObjectPool#getFairness()}
*/
- int getNumIdle();
+ boolean getLifo();
/**
- * See {@link GenericObjectPool#getNumTestsPerEvictionRun()}
- * @return See {@link GenericObjectPool#getNumTestsPerEvictionRun()}
+ * See {@link GenericObjectPool#getLogAbandoned()}
+ * @return See {@link GenericObjectPool#getLogAbandoned()}
*/
- int getNumTestsPerEvictionRun();
+ boolean getLogAbandoned();
/**
- * See {@link GenericObjectPool#getTestOnCreate()}
- * @return See {@link GenericObjectPool#getTestOnCreate()}
- * @since 2.2
+ * See {@link GenericObjectPool#getMaxBorrowWaitTimeMillis()}
+ * @return See {@link GenericObjectPool#getMaxBorrowWaitTimeMillis()}
*/
- boolean getTestOnCreate();
+ long getMaxBorrowWaitTimeMillis();
/**
- * See {@link GenericObjectPool#getTestOnBorrow()}
- * @return See {@link GenericObjectPool#getTestOnBorrow()}
+ * See {@link GenericObjectPool#getMaxIdle()}
+ * @return See {@link GenericObjectPool#getMaxIdle()}
*/
- boolean getTestOnBorrow();
+ int getMaxIdle();
/**
- * See {@link GenericObjectPool#getTestOnReturn()}
- * @return See {@link GenericObjectPool#getTestOnReturn()}
+ * See {@link GenericObjectPool#getMaxTotal()}
+ * @return See {@link GenericObjectPool#getMaxTotal()}
*/
- boolean getTestOnReturn();
+ int getMaxTotal();
/**
- * See {@link GenericObjectPool#getTestWhileIdle()}
- * @return See {@link GenericObjectPool#getTestWhileIdle()}
+ * See {@link GenericObjectPool#getMaxWaitMillis()}
+ * @return See {@link GenericObjectPool#getMaxWaitMillis()}
*/
- boolean getTestWhileIdle();
+ long getMaxWaitMillis();
/**
- * See {@link GenericObjectPool#getTimeBetweenEvictionRunsMillis()}
- * @return See {@link GenericObjectPool#getTimeBetweenEvictionRunsMillis()}
+ * See {@link GenericObjectPool#getMeanActiveTimeMillis()}
+ * @return See {@link GenericObjectPool#getMeanActiveTimeMillis()}
*/
- long getTimeBetweenEvictionRunsMillis();
+ long getMeanActiveTimeMillis();
/**
- * See {@link GenericObjectPool#isClosed()}
- * @return See {@link GenericObjectPool#isClosed()}
+ * See {@link GenericObjectPool#getMeanBorrowWaitTimeMillis()}
+ * @return See {@link GenericObjectPool#getMeanBorrowWaitTimeMillis()}
*/
- boolean isClosed();
+ long getMeanBorrowWaitTimeMillis();
// Getters for monitoring attributes
/**
- * See {@link GenericObjectPool#getBorrowedCount()}
- * @return See {@link GenericObjectPool#getBorrowedCount()}
+ * See {@link GenericObjectPool#getMeanIdleTimeMillis()}
+ * @return See {@link GenericObjectPool#getMeanIdleTimeMillis()}
*/
- long getBorrowedCount();
+ long getMeanIdleTimeMillis();
/**
- * See {@link GenericObjectPool#getReturnedCount()}
- * @return See {@link GenericObjectPool#getReturnedCount()}
+ * See {@link GenericObjectPool#getMinEvictableIdleTimeMillis()}
+ * @return See {@link GenericObjectPool#getMinEvictableIdleTimeMillis()}
*/
- long getReturnedCount();
+ long getMinEvictableIdleTimeMillis();
/**
- * See {@link GenericObjectPool#getCreatedCount()}
- * @return See {@link GenericObjectPool#getCreatedCount()}
+ * See {@link GenericObjectPool#getMinIdle()}
+ * @return See {@link GenericObjectPool#getMinIdle()}
*/
- long getCreatedCount();
+ int getMinIdle();
/**
- * See {@link GenericObjectPool#getDestroyedCount()}
- * @return See {@link GenericObjectPool#getDestroyedCount()}
+ * See {@link GenericObjectPool#getNumActive()}
+ * @return See {@link GenericObjectPool#getNumActive()}
*/
- long getDestroyedCount();
+ int getNumActive();
/**
- * See {@link GenericObjectPool#getDestroyedByEvictorCount()}
- * @return See {@link GenericObjectPool#getDestroyedByEvictorCount()}
+ * See {@link GenericObjectPool#getNumIdle()}
+ * @return See {@link GenericObjectPool#getNumIdle()}
*/
- long getDestroyedByEvictorCount();
+ int getNumIdle();
/**
- * See {@link GenericObjectPool#getDestroyedByBorrowValidationCount()}
- * @return See {@link GenericObjectPool#getDestroyedByBorrowValidationCount()}
+ * See {@link GenericObjectPool#getNumTestsPerEvictionRun()}
+ * @return See {@link GenericObjectPool#getNumTestsPerEvictionRun()}
*/
- long getDestroyedByBorrowValidationCount();
+ int getNumTestsPerEvictionRun();
/**
- * See {@link GenericObjectPool#getMeanActiveTimeMillis()}
- * @return See {@link GenericObjectPool#getMeanActiveTimeMillis()}
+ * See {@link GenericObjectPool#getNumWaiters()}
+ * @return See {@link GenericObjectPool#getNumWaiters()}
*/
- long getMeanActiveTimeMillis();
+ int getNumWaiters();
/**
- * See {@link GenericObjectPool#getMeanIdleTimeMillis()}
- * @return See {@link GenericObjectPool#getMeanIdleTimeMillis()}
+ * See {@link GenericObjectPool#getRemoveAbandonedOnBorrow()}
+ * @return See {@link GenericObjectPool#getRemoveAbandonedOnBorrow()}
*/
- long getMeanIdleTimeMillis();
+ boolean getRemoveAbandonedOnBorrow();
/**
- * See {@link GenericObjectPool#getMeanBorrowWaitTimeMillis()}
- * @return See {@link GenericObjectPool#getMeanBorrowWaitTimeMillis()}
+ * See {@link GenericObjectPool#getRemoveAbandonedOnMaintenance()}
+ * @return See {@link GenericObjectPool#getRemoveAbandonedOnMaintenance()}
*/
- long getMeanBorrowWaitTimeMillis();
+ boolean getRemoveAbandonedOnMaintenance();
/**
- * See {@link GenericObjectPool#getMaxBorrowWaitTimeMillis()}
- * @return See {@link GenericObjectPool#getMaxBorrowWaitTimeMillis()}
+ * See {@link GenericObjectPool#getRemoveAbandonedTimeout()}
+ * @return See {@link GenericObjectPool#getRemoveAbandonedTimeout()}
*/
- long getMaxBorrowWaitTimeMillis();
+ int getRemoveAbandonedTimeout();
/**
- * See {@link GenericObjectPool#getCreationStackTrace()}
- * @return See {@link GenericObjectPool#getCreationStackTrace()}
+ * See {@link GenericObjectPool#getReturnedCount()}
+ * @return See {@link GenericObjectPool#getReturnedCount()}
*/
- String getCreationStackTrace();
+ long getReturnedCount();
/**
- * See {@link GenericObjectPool#getNumWaiters()}
- * @return See {@link GenericObjectPool#getNumWaiters()}
+ * See {@link GenericObjectPool#getTestOnBorrow()}
+ * @return See {@link GenericObjectPool#getTestOnBorrow()}
*/
- int getNumWaiters();
+ boolean getTestOnBorrow();
// Getters for abandoned object removal configuration
/**
- * See {@link GenericObjectPool#isAbandonedConfig()}
- * @return See {@link GenericObjectPool#isAbandonedConfig()}
+ * See {@link GenericObjectPool#getTestOnCreate()}
+ * @return See {@link GenericObjectPool#getTestOnCreate()}
+ * @since 2.2
*/
- boolean isAbandonedConfig();
+ boolean getTestOnCreate();
/**
- * See {@link GenericObjectPool#getLogAbandoned()}
- * @return See {@link GenericObjectPool#getLogAbandoned()}
+ * See {@link GenericObjectPool#getTestOnReturn()}
+ * @return See {@link GenericObjectPool#getTestOnReturn()}
*/
- boolean getLogAbandoned();
+ boolean getTestOnReturn();
/**
- * See {@link GenericObjectPool#getRemoveAbandonedOnBorrow()}
- * @return See {@link GenericObjectPool#getRemoveAbandonedOnBorrow()}
+ * See {@link GenericObjectPool#getTestWhileIdle()}
+ * @return See {@link GenericObjectPool#getTestWhileIdle()}
*/
- boolean getRemoveAbandonedOnBorrow();
+ boolean getTestWhileIdle();
/**
- * See {@link GenericObjectPool#getRemoveAbandonedOnMaintenance()}
- * @return See {@link GenericObjectPool#getRemoveAbandonedOnMaintenance()}
+ * See {@link GenericObjectPool#getTimeBetweenEvictionRunsMillis()}
+ * @return See {@link GenericObjectPool#getTimeBetweenEvictionRunsMillis()}
*/
- boolean getRemoveAbandonedOnMaintenance();
+ long getTimeBetweenEvictionRunsMillis();
/**
- * See {@link GenericObjectPool#getRemoveAbandonedTimeout()}
- * @return See {@link GenericObjectPool#getRemoveAbandonedTimeout()}
+ * See {@link GenericObjectPool#isAbandonedConfig()}
+ * @return See {@link GenericObjectPool#isAbandonedConfig()}
*/
- int getRemoveAbandonedTimeout();
+ boolean isAbandonedConfig();
/**
- * See {@link GenericObjectPool#getFactoryType()}
- * @return See {@link GenericObjectPool#getFactoryType()}
+ * See {@link GenericObjectPool#isClosed()}
+ * @return See {@link GenericObjectPool#isClosed()}
*/
- String getFactoryType();
+ boolean isClosed();
/**
* See {@link GenericObjectPool#listAllObjects()}
diff --git a/src/main/java/org/apache/commons/pool2/impl/NoOpCallStack.java b/src/main/java/org/apache/commons/pool2/impl/NoOpCallStack.java
index 835742c..6cf4bd7 100644
--- a/src/main/java/org/apache/commons/pool2/impl/NoOpCallStack.java
+++ b/src/main/java/org/apache/commons/pool2/impl/NoOpCallStack.java
@@ -38,8 +38,8 @@ public class NoOpCallStack implements CallStack {
}
@Override
- public boolean printStackTrace(final PrintWriter writer) {
- return false;
+ public void clear() {
+ // no-op
}
@Override
@@ -48,7 +48,7 @@ public class NoOpCallStack implements CallStack {
}
@Override
- public void clear() {
- // no-op
+ public boolean printStackTrace(final PrintWriter writer) {
+ return false;
}
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/PooledSoftReference.java b/src/main/java/org/apache/commons/pool2/impl/PooledSoftReference.java
index 2e3c54c..4984cc8 100644
--- a/src/main/java/org/apache/commons/pool2/impl/PooledSoftReference.java
+++ b/src/main/java/org/apache/commons/pool2/impl/PooledSoftReference.java
@@ -57,23 +57,6 @@ public class PooledSoftReference<T> extends DefaultPooledObject<T> {
}
/**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- final StringBuilder result = new StringBuilder();
- result.append("Referenced Object: ");
- result.append(getObject().toString());
- result.append(", State: ");
- synchronized (this) {
- result.append(getState().toString());
- }
- return result.toString();
- // TODO add other attributes
- // TODO encapsulate state and other attribute display in parent
- }
-
- /**
* Gets the SoftReference wrapped by this object.
*
* @return underlying SoftReference
@@ -95,4 +78,21 @@ public class PooledSoftReference<T> extends DefaultPooledObject<T> {
public synchronized void setReference(final SoftReference<T> reference) {
this.reference = reference;
}
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String toString() {
+ final StringBuilder result = new StringBuilder();
+ result.append("Referenced Object: ");
+ result.append(getObject().toString());
+ result.append(", State: ");
+ synchronized (this) {
+ result.append(getState().toString());
+ }
+ return result.toString();
+ // TODO add other attributes
+ // TODO encapsulate state and other attribute display in parent
+ }
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/SecurityManagerCallStack.java b/src/main/java/org/apache/commons/pool2/impl/SecurityManagerCallStack.java
index 26936b1..6225d4e 100644
--- a/src/main/java/org/apache/commons/pool2/impl/SecurityManagerCallStack.java
+++ b/src/main/java/org/apache/commons/pool2/impl/SecurityManagerCallStack.java
@@ -36,9 +36,45 @@ import java.util.List;
*/
public class SecurityManagerCallStack implements CallStack {
+ /**
+ * A custom security manager.
+ */
+ private static class PrivateSecurityManager extends SecurityManager {
+ /**
+ * Get the class stack.
+ *
+ * @return class stack
+ */
+ private List<WeakReference<Class<?>>> getCallStack() {
+ final Class<?>[] classes = getClassContext();
+ final List<WeakReference<Class<?>>> stack = new ArrayList<>(classes.length);
+ for (final Class<?> klass : classes) {
+ stack.add(new WeakReference<Class<?>>(klass));
+ }
+ return stack;
+ }
+ }
+ /**
+ * A snapshot of a class stack.
+ */
+ private static class Snapshot {
+ private final long timestampMillis = System.currentTimeMillis();
+ private final List<WeakReference<Class<?>>> stack;
+
+ /**
+ * Create a new snapshot with a class stack.
+ *
+ * @param stack class stack
+ */
+ private Snapshot(final List<WeakReference<Class<?>>> stack) {
+ this.stack = stack;
+ }
+ }
private final String messageFormat;
+
//@GuardedBy("dateFormat")
private final DateFormat dateFormat;
+
private final PrivateSecurityManager securityManager;
private volatile Snapshot snapshot;
@@ -56,6 +92,16 @@ public class SecurityManagerCallStack implements CallStack {
}
@Override
+ public void clear() {
+ snapshot = null;
+ }
+
+ @Override
+ public void fillInStackTrace() {
+ snapshot = new Snapshot(securityManager.getCallStack());
+ }
+
+ @Override
public boolean printStackTrace(final PrintWriter writer) {
final Snapshot snapshotRef = this.snapshot;
if (snapshotRef == null) {
@@ -75,50 +121,4 @@ public class SecurityManagerCallStack implements CallStack {
}
return true;
}
-
- @Override
- public void fillInStackTrace() {
- snapshot = new Snapshot(securityManager.getCallStack());
- }
-
- @Override
- public void clear() {
- snapshot = null;
- }
-
- /**
- * A custom security manager.
- */
- private static class PrivateSecurityManager extends SecurityManager {
- /**
- * Get the class stack.
- *
- * @return class stack
- */
- private List<WeakReference<Class<?>>> getCallStack() {
- final Class<?>[] classes = getClassContext();
- final List<WeakReference<Class<?>>> stack = new ArrayList<>(classes.length);
- for (final Class<?> klass : classes) {
- stack.add(new WeakReference<Class<?>>(klass));
- }
- return stack;
- }
- }
-
- /**
- * A snapshot of a class stack.
- */
- private static class Snapshot {
- private final long timestampMillis = System.currentTimeMillis();
- private final List<WeakReference<Class<?>>> stack;
-
- /**
- * Create a new snapshot with a class stack.
- *
- * @param stack class stack
- */
- private Snapshot(final List<WeakReference<Class<?>>> stack) {
- this.stack = stack;
- }
- }
}
diff --git a/src/main/java/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java b/src/main/java/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java
index eee0ff1..1c6e7a7 100644
--- a/src/main/java/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java
+++ b/src/main/java/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java
@@ -79,6 +79,64 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
}
/**
+ * Creates an object, and places it into the pool. addObject() is useful for
+ * "pre-loading" a pool with idle objects.
+ * <p>
+ * Before being added to the pool, the newly created instance is
+ * {@link PooledObjectFactory#validateObject(
+ * org.apache.commons.pool2.PooledObject) validated} and
+ * {@link PooledObjectFactory#passivateObject(
+ * org.apache.commons.pool2.PooledObject) passivated}. If
+ * validation fails, the new instance is
+ * {@link PooledObjectFactory#destroyObject(
+ * org.apache.commons.pool2.PooledObject) destroyed}. Exceptions
+ * generated by the factory {@code makeObject} or
+ * {@code passivate} are propagated to the caller. Exceptions
+ * destroying instances are silently swallowed.
+ *
+ * @throws IllegalStateException
+ * if invoked on a {@link #close() closed} pool
+ * @throws Exception
+ * when the {@link #getFactory() factory} has a problem creating
+ * or passivating an object.
+ */
+ @Override
+ public synchronized void addObject() throws Exception {
+ assertOpen();
+ if (factory == null) {
+ throw new IllegalStateException(
+ "Cannot add objects without a factory.");
+ }
+ final T obj = factory.makeObject().getObject();
+ createCount++;
+ // Create and register with the queue
+ final PooledSoftReference<T> ref = new PooledSoftReference<>(
+ new SoftReference<>(obj, refQueue));
+ allReferences.add(ref);
+
+ boolean success = true;
+ if (!factory.validateObject(ref)) {
+ success = false;
+ } else {
+ factory.passivateObject(ref);
+ }
+
+ final boolean shouldDestroy = !success;
+ if (success) {
+ idleReferences.add(ref);
+ notifyAll(); // numActive has changed
+ }
+
+ if (shouldDestroy) {
+ try {
+ destroy(ref);
+ } catch (final Exception e) {
+ // ignored
+ }
+ }
+ }
+
+ /**
* Borrows an object from the pool. If there are no idle instances available
* in the pool, the configured factory's
* {@link PooledObjectFactory#makeObject()} method is invoked to create a
@@ -169,163 +227,6 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
}
/**
- * Returns an instance to the pool after successful validation and
- * passivation. The returning instance is destroyed if any of the following
- * are true:
- * <ul>
- * <li>the pool is closed</li>
- * <li>{@link PooledObjectFactory#validateObject(
- * org.apache.commons.pool2.PooledObject) validation} fails
- * </li>
- * <li>{@link PooledObjectFactory#passivateObject(
- * org.apache.commons.pool2.PooledObject) passivation}
- * throws an exception</li>
- * </ul>
- * Exceptions passivating or destroying instances are silently swallowed.
- * Exceptions validating instances are propagated to the client.
- *
- * @param obj
- * instance to return to the pool
- * @throws IllegalArgumentException
- * if obj is not currently part of this pool
- */
- @Override
- public synchronized void returnObject(final T obj) throws Exception {
- boolean success = !isClosed();
- final PooledSoftReference<T> ref = findReference(obj);
- if (ref == null) {
- throw new IllegalStateException(
- "Returned object not currently part of this pool");
- }
- if (factory != null) {
- if (!factory.validateObject(ref)) {
- success = false;
- } else {
- try {
- factory.passivateObject(ref);
- } catch (final Exception e) {
- success = false;
- }
- }
- }
-
- final boolean shouldDestroy = !success;
- numActive--;
- if (success) {
-
- // Deallocate and add to the idle instance pool
- ref.deallocate();
- idleReferences.add(ref);
- }
- notifyAll(); // numActive has changed
-
- if (shouldDestroy && factory != null) {
- try {
- destroy(ref);
- } catch (final Exception e) {
- // ignored
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public synchronized void invalidateObject(final T obj) throws Exception {
- final PooledSoftReference<T> ref = findReference(obj);
- if (ref == null) {
- throw new IllegalStateException(
- "Object to invalidate is not currently part of this pool");
- }
- if (factory != null) {
- destroy(ref);
- }
- numActive--;
- notifyAll(); // numActive has changed
- }
-
- /**
- * Creates an object, and places it into the pool. addObject() is useful for
- * "pre-loading" a pool with idle objects.
- * <p>
- * Before being added to the pool, the newly created instance is
- * {@link PooledObjectFactory#validateObject(
- * org.apache.commons.pool2.PooledObject) validated} and
- * {@link PooledObjectFactory#passivateObject(
- * org.apache.commons.pool2.PooledObject) passivated}. If
- * validation fails, the new instance is
- * {@link PooledObjectFactory#destroyObject(
- * org.apache.commons.pool2.PooledObject) destroyed}. Exceptions
- * generated by the factory {@code makeObject} or
- * {@code passivate} are propagated to the caller. Exceptions
- * destroying instances are silently swallowed.
- *
- * @throws IllegalStateException
- * if invoked on a {@link #close() closed} pool
- * @throws Exception
- * when the {@link #getFactory() factory} has a problem creating
- * or passivating an object.
- */
- @Override
- public synchronized void addObject() throws Exception {
- assertOpen();
- if (factory == null) {
- throw new IllegalStateException(
- "Cannot add objects without a factory.");
- }
- final T obj = factory.makeObject().getObject();
- createCount++;
- // Create and register with the queue
- final PooledSoftReference<T> ref = new PooledSoftReference<>(
- new SoftReference<>(obj, refQueue));
- allReferences.add(ref);
-
- boolean success = true;
- if (!factory.validateObject(ref)) {
- success = false;
- } else {
- factory.passivateObject(ref);
- }
-
- final boolean shouldDestroy = !success;
- if (success) {
- idleReferences.add(ref);
- notifyAll(); // numActive has changed
- }
-
- if (shouldDestroy) {
- try {
- destroy(ref);
- } catch (final Exception e) {
- // ignored
- }
- }
- }
-
- /**
- * Gets an approximation not less than the of the number of idle
- * instances in the pool.
- *
- * @return estimated number of idle instances in the pool
- */
- @Override
- public synchronized int getNumIdle() {
- pruneClearedReferences();
- return idleReferences.size();
- }
-
- /**
- * Gets the number of instances currently borrowed from this pool.
- *
- * @return the number of instances currently borrowed from this pool
- */
- @Override
- public synchronized int getNumActive() {
- return numActive;
- }
-
- /**
* Clears any objects sitting idle in the pool.
*/
@Override
@@ -362,25 +263,22 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
}
/**
- * Gets the {@link PooledObjectFactory} used by this pool to create and
- * manage object instances.
+ * Destroys a {@code PooledSoftReference} and removes it from the idle and all
+ * references pools.
*
- * @return the factory
- */
- public synchronized PooledObjectFactory<T> getFactory() {
- return factory;
- }
-
- /**
- * If any idle objects were garbage collected, remove their
- * {@link Reference} wrappers from the idle object pool.
+ * @param toDestroy PooledSoftReference to destroy
+ *
+ * @throws Exception If an error occurs while trying to destroy the object
*/
- private void pruneClearedReferences() {
- // Remove wrappers for enqueued references from idle and allReferences lists
- removeClearedReferences(idleReferences.iterator());
- removeClearedReferences(allReferences.iterator());
- while (refQueue.poll() != null) {
- // empty
+ private void destroy(final PooledSoftReference<T> toDestroy) throws Exception {
+ toDestroy.invalidate();
+ idleReferences.remove(toDestroy);
+ allReferences.remove(toDestroy);
+ try {
+ factory.destroyObject(toDestroy);
+ } finally {
+ destroyCount++;
+ toDestroy.getReference().clear();
}
}
@@ -402,22 +300,64 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
}
/**
- * Destroys a {@code PooledSoftReference} and removes it from the idle and all
- * references pools.
+ * Gets the {@link PooledObjectFactory} used by this pool to create and
+ * manage object instances.
*
- * @param toDestroy PooledSoftReference to destroy
+ * @return the factory
+ */
+ public synchronized PooledObjectFactory<T> getFactory() {
+ return factory;
+ }
+
+ /**
+ * Gets the number of instances currently borrowed from this pool.
*
- * @throws Exception If an error occurs while trying to destroy the object
+ * @return the number of instances currently borrowed from this pool
*/
- private void destroy(final PooledSoftReference<T> toDestroy) throws Exception {
- toDestroy.invalidate();
- idleReferences.remove(toDestroy);
- allReferences.remove(toDestroy);
- try {
- factory.destroyObject(toDestroy);
- } finally {
- destroyCount++;
- toDestroy.getReference().clear();
+ @Override
+ public synchronized int getNumActive() {
+ return numActive;
+ }
+
+ /**
+ * Gets an approximation not less than the of the number of idle
+ * instances in the pool.
+ *
+ * @return estimated number of idle instances in the pool
+ */
+ @Override
+ public synchronized int getNumIdle() {
+ pruneClearedReferences();
+ return idleReferences.size();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public synchronized void invalidateObject(final T obj) throws Exception {
+ final PooledSoftReference<T> ref = findReference(obj);
+ if (ref == null) {
+ throw new IllegalStateException(
+ "Object to invalidate is not currently part of this pool");
+ }
+ if (factory != null) {
+ destroy(ref);
+ }
+ numActive--;
+ notifyAll(); // numActive has changed
+ }
+
+ /**
+ * If any idle objects were garbage collected, remove their
+ * {@link Reference} wrappers from the idle object pool.
+ */
+ private void pruneClearedReferences() {
+ // Remove wrappers for enqueued references from idle and allReferences lists
+ removeClearedReferences(idleReferences.iterator());
+ removeClearedReferences(allReferences.iterator());
+ while (refQueue.poll() != null) {
+ // empty
}
}
@@ -435,6 +375,66 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
}
}
+ /**
+ * Returns an instance to the pool after successful validation and
+ * passivation. The returning instance is destroyed if any of the following
+ * are true:
+ * <ul>
+ * <li>the pool is closed</li>
+ * <li>{@link PooledObjectFactory#validateObject(
+ * org.apache.commons.pool2.PooledObject) validation} fails
+ * </li>
+ * <li>{@link PooledObjectFactory#passivateObject(
+ * org.apache.commons.pool2.PooledObject) passivation}
+ * throws an exception</li>
+ * </ul>
+ * Exceptions passivating or destroying instances are silently swallowed.
+ * Exceptions validating instances are propagated to the client.
+ *
+ * @param obj
+ * instance to return to the pool
+ * @throws IllegalArgumentException
+ * if obj is not currently part of this pool
+ */
+ @Override
+ public synchronized void returnObject(final T obj) throws Exception {
+ boolean success = !isClosed();
+ final PooledSoftReference<T> ref = findReference(obj);
+ if (ref == null) {
+ throw new IllegalStateException(
+ "Returned object not currently part of this pool");
+ }
+ if (factory != null) {
+ if (!factory.validateObject(ref)) {
+ success = false;
+ } else {
+ try {
+ factory.passivateObject(ref);
+ } catch (final Exception e) {
+ success = false;
+ }
+ }
+ }
+
+ final boolean shouldDestroy = !success;
+ numActive--;
+ if (success) {
+
+ // Deallocate and add to the idle instance pool
+ ref.deallocate();
+ idleReferences.add(ref);
+ }
+ notifyAll(); // numActive has changed
+
+ if (shouldDestroy && factory != null) {
+ try {
+ destroy(ref);
+ } catch (final Exception e) {
+ // ignored
+ }
+ }
+ }
+
@Override
protected void toStringAppendFields(final StringBuilder builder) {
super.toStringAppendFields(builder);
diff --git a/src/main/java/org/apache/commons/pool2/impl/ThrowableCallStack.java b/src/main/java/org/apache/commons/pool2/impl/ThrowableCallStack.java
index 2ace1b7..7219038 100644
--- a/src/main/java/org/apache/commons/pool2/impl/ThrowableCallStack.java
+++ b/src/main/java/org/apache/commons/pool2/impl/ThrowableCallStack.java
@@ -30,7 +30,15 @@ import java.text.SimpleDateFormat;
*/
public class ThrowableCallStack implements CallStack {
+ /**
+ * A snapshot of a throwable.
+ */
+ private static class Snapshot extends Throwable {
+ private static final long serialVersionUID = 1L;
+ private final long timestampMillis = System.currentTimeMillis();
+ }
private final String messageFormat;
+
//@GuardedBy("dateFormat")
private final DateFormat dateFormat;
@@ -48,6 +56,16 @@ public class ThrowableCallStack implements CallStack {
}
@Override
+ public void clear() {
+ snapshot = null;
+ }
+
+ @Override
+ public void fillInStackTrace() {
+ snapshot = new Snapshot();
+ }
+
+ @Override
public synchronized boolean printStackTrace(final PrintWriter writer) {
final Snapshot snapshotRef = this.snapshot;
if (snapshotRef == null) {
@@ -65,22 +83,4 @@ public class ThrowableCallStack implements CallStack {
snapshotRef.printStackTrace(writer);
return true;
}
-
- @Override
- public void fillInStackTrace() {
- snapshot = new Snapshot();
- }
-
- @Override
- public void clear() {
- snapshot = null;
- }
-
- /**
- * A snapshot of a throwable.
- */
- private static class Snapshot extends Throwable {
- private static final long serialVersionUID = 1L;
- private final long timestampMillis = System.currentTimeMillis();
- }
}