T - the type of reusable objects held in this poolpublic abstract class ObjectPool<T extends Reusable> extends Object implements Comparable<ObjectPool<T>>
New objects are retrieved on demand according to specified limits, and the pool can also ensure an object's validity before returning it. The limits which can be set for a pool include the number of items to be held in the pool (minimum/maximum), and the maximum number to ever be created.
Up to a maximum of maxSize items can exist simultaneously,
but a maximum of maxPool are ever held in the pool for quick
availability. The pool tries to maintain at least minPool items
available for use even when the pool is not being used. As a result, if
idleTimeout is enabled the number of available pooled items may reduce from
maxPool down towards minPool if items are not used
frequently.
ObjectPool should be sub-classed to override at least
the following methods:
protected T create() throws Exception protected boolean isValid(final T o) protected void destroy(final T o)
and optionally the following methods, which can be used for resource cleanup as required:
protected preRelease() protected postRelease()
It is recommended that the sub-class implements methods for obtaining
and returning items within the pool, casting the objects returned by this
class as required to the appropriate class type. It is also recommended
that the sub-class up-casts items to a user-defined interface when handing
them to pool clients, to prevent clients tampering with class internals.
For example, a database ConnectionPool class might sub-class ObjectPool,
but only hand over instances cast to the java.sql.Connection
interface.
Idle timeout of pooled items is handled by the idleTimeout
parameter, which by default is specified in milliseconds. Sub-classes
wanting to rescale to a different time unit should override the
getIdleTimeoutMultiplier() method to return the appropriate value.
This class also support asynchronous destruction of items, which can be
useful in circumstances where destruction of items held can take a long
time which would delay the checkIn method. This also applies
to the release of the pool after its final use, which should always be
done using one of the release... methods.
| Modifier and Type | Class and Description |
|---|---|
static class |
ObjectPool.Strategy
Enumeration of selection strategies.
|
| Modifier and Type | Field and Description |
|---|---|
protected org.slf4j.Logger |
log
SLF4J logger instance for writing log entries.
|
| Modifier | Constructor and Description |
|---|---|
protected |
ObjectPool(String name,
int minPool,
int maxPool,
int maxSize,
long idleTimeout)
Creates new object pool.
|
protected |
ObjectPool(String name,
int maxPool,
int maxSize,
long idleTimeout)
Creates new object pool (with
minPool=0). |
| Modifier and Type | Method and Description |
|---|---|
void |
addObjectPoolListener(ObjectPoolListener<T> x)
Adds an listener to the event notification list.
|
void |
checkIn(T o)
Checks an object into the pool, and notifies other threads that may be
waiting for one to become available.
|
T |
checkOut()
Checks out an item from the pool.
|
T |
checkOut(long timeout)
Checks out an item from the pool.
|
int |
compareTo(ObjectPool<T> pool)
Compares this object with the specified object for order.
|
protected abstract T |
create()
Object creation method.
|
protected abstract void |
destroy(T o)
Object destruction method.
|
boolean |
equals(Object o)
Indicates whether some other object is "equal to" this one.
|
void |
flush()
Flushes the pool of all currently available items, emptying the pool.
|
int |
getCheckedOut()
Returns the number of items that are currently checked-out.
|
LogUtil |
getCustomLogger()
Returns the custom
LogUtil instance being used,
or null if it doesn't exist. |
int |
getFreeCount()
Returns the number of items held in the pool that are free to be checked-out.
|
long |
getIdleTimeout()
Returns the idle timeout for unused items in the pool.
|
protected float |
getIdleTimeoutMultiplier()
Returns the multiplier for adjusting the idle timeout unit.
|
protected long |
getIdleTimeoutUnadjusted()
Returns the idle timeout for unused items in the pool (in milliseconds).
|
protected long |
getMaximumCleaningInterval()
Specifies the maximum time interval between cleaning attempts of
the
Cleaner thread (milliseconds). |
int |
getMaxPool()
Returns the maximum number of items that can be pooled.
|
int |
getMaxSize()
Returns the maximum number of items that can be created.
|
protected long |
getMinimumCleaningInterval()
Specifies the minimum time interval between cleaning attempts of
the
Cleaner thread (milliseconds). |
int |
getMinPool()
Returns the minimum number of items that should be kept pooled.
|
String |
getName()
Returns the pool name.
|
String |
getParametersString()
Returns a summary string of the pool's parameters.
|
protected Class<? extends List> |
getPoolClass()
Returns the class to use for the pool collection.
|
float |
getPoolHitRate()
Returns hit rate of the pool (between 0 and 1).
|
float |
getPoolMissRate()
Returns miss rate of the pool (between 0 and 1).
|
long |
getRequestCount()
Returns the number of check-out requests that have been made to the pool
since either its creation or the last time the
resetHitCounter()
method was called. |
int |
getSize()
Returns the total number of objects held (available and checked-out).
|
int |
hashCode()
Returns a hash code value for the object.
|
void |
init()
Initializes the pool with the default (i.e.
|
void |
init(int num)
Asynchronously initializes up to the specified number of items in the pool.
|
boolean |
isAsyncDestroy()
Returns whether asynchronous object destruction is enabled.
|
boolean |
isReleased()
Returns whether the pool has been released (and can no longer be used).
|
protected abstract boolean |
isValid(T o)
Object validation method.
|
protected void |
log_debug(String s)
Logging relay method (to prefix pool name).
|
protected void |
log_debug(String s,
Throwable throwable)
Logging relay method (to prefix pool name).
|
protected void |
log_error(String s)
Logging relay method (to prefix pool name).
|
protected void |
log_error(String s,
Throwable throwable)
Logging relay method (to prefix pool name).
|
protected void |
log_info(String s)
Logging relay method (to prefix pool name).
|
protected void |
log_info(String s,
Throwable throwable)
Logging relay method (to prefix pool name).
|
protected void |
log_trace(String s)
Logging relay method (to prefix pool name).
|
protected void |
log_trace(String s,
Throwable throwable)
Logging relay method (to prefix pool name).
|
protected void |
log_warn(String s)
Logging relay method (to prefix pool name).
|
protected void |
log_warn(String s,
Throwable throwable)
Logging relay method (to prefix pool name).
|
protected void |
postRelease()
Method to give a sub-class the opportunity to cleanup resources after
the pool is officially released.
|
protected void |
preRelease()
Method to give a sub-class the opportunity to cleanup resources before
the pool is officially released.
|
void |
registerShutdownHook()
Registers a shutdown hook for this ConnectionPoolManager instance
to ensure it is released if the JVM exits.
|
void |
release()
Releases all items from the pool, and shuts the pool down.
|
void |
release(long timeout)
Releases all items from the pool, and shuts the pool down, allowing
timeout milliseconds for the connections to be gracefully returned
to the pool before they are forcibly destroyed. |
void |
releaseAsync()
Releases all items from the pool, and shuts the pool down.
|
void |
releaseAsync(long timeout)
Releases all items from the pool, and shuts the pool down.
|
void |
releaseForcibly()
Deprecated.
Use
releaseImmediately() instead |
void |
releaseImmediately()
Immediately releases all items from the pool, and shuts the pool down.
|
void |
removeObjectPoolListener(ObjectPoolListener<T> x)
Removes a listener from the event notification list.
|
void |
removeShutdownHook()
Unregisters a registered shutdown hook for this ConnectionPoolManager instance.
|
void |
resetHitCounter()
Resets the counters for determining the pool's hit/miss rates.
|
void |
setAsyncDestroy(boolean b)
Determines whether to perform asynchronous object destruction.
|
void |
setLog(PrintWriter writer)
Sets the custom log stream.
|
void |
setParameters(int minPool,
int maxPool,
int maxSize,
long idleTimeout)
Sets the pooling parameters.
|
void |
setParameters(int maxPool,
int maxSize,
long idleTimeout)
Sets the pooling parameters (excluding
minPool). |
void |
setSelectionStrategy(ObjectPool.Strategy selection)
Sets the pool selection strategy.
|
String |
toString()
Returns a descriptive string for this pool instance.
|
protected ObjectPool(String name, int minPool, int maxPool, int maxSize, long idleTimeout)
name - pool nameminPool - minimum number of pooled objects, or 0 for nonemaxPool - maximum number of pooled objects, or 0 for nonemaxSize - maximum number of possible objects, or 0 for no limitidleTimeout - idle timeout for pooled objects, or 0 for no timeoutprotected ObjectPool(String name, int maxPool, int maxSize, long idleTimeout)
minPool=0).name - pool namemaxPool - maximum number of pooled objects, or 0 for nonemaxSize - maximum number of possible objects, or 0 for no limitidleTimeout - idle timeout for pooled objects, or 0 for no timeoutpublic void registerShutdownHook()
public void removeShutdownHook()
public String toString()
public String getParametersString()
public final void init()
public final void init(int num)
This method is somewhat redundant since the introduction
of the minPool parameter, which should be used preferentially where
applicable. It can sometimes be useful to create initial pooled items
for a pool with minPool=0.
num - number of objects to initializepublic final T checkOut() throws Exception
null if nothing availableException - if there is an error creating a new objectpublic final T checkOut(long timeout) throws Exception
timeout - timeout value in millisecondsnull if nothing available within timeout periodException - if there is an error creating a new objectpublic final void checkIn(T o)
o - object to check inpublic final void release()
public final boolean isReleased()
@Deprecated public final void releaseForcibly()
releaseImmediately() insteadrelease(long) method. The equivalent behaviour
can be achieved using releaseImmediately().public final void releaseImmediately()
public final void releaseAsync()
public final void releaseAsync(long timeout)
public final void release(long timeout)
timeout milliseconds for the connections to be gracefully returned
to the pool before they are forcibly destroyed.
A negative timeout is equivalent to no timeout, and the method will wait
for items to be checked in before destruction. If timeout >= 0 then
items will be forcibly destroyed after the specified time has elapsed.timeout - timeout after which to forcibly destroy items (-1 for no timeout)protected void preRelease()
ObjectPool release implementation.protected void postRelease()
ObjectPool release implementation.
Be aware that the event-dispatch thread, cleaner thread, any init threads,
and the custom log have all been terminated before this method is called.protected abstract T create() throws Exception
Exception - if unable to create the itemprotected abstract boolean isValid(T o)
o - object to check for validityprotected abstract void destroy(T o)
o - object to destroypublic final void setAsyncDestroy(boolean b)
b - whether to enable asynchronous object destructionpublic final boolean isAsyncDestroy()
public void setLog(PrintWriter writer)
PrintWriter
to receive log information.writer - PrintWriter to which to write log entriespublic LogUtil getCustomLogger()
LogUtil instance being used,
or null if it doesn't exist.LogUtil instance being used,
or null if it doesn't existprotected void log_error(String s)
s - string to logprotected void log_error(String s, Throwable throwable)
s - string to logthrowable - Throwable instance to logprotected void log_warn(String s)
s - string to logprotected void log_warn(String s, Throwable throwable)
s - string to logthrowable - Throwable instance to logprotected void log_info(String s)
s - string to logprotected void log_info(String s, Throwable throwable)
s - string to logthrowable - Throwable instance to logprotected void log_debug(String s)
s - string to logprotected void log_debug(String s, Throwable throwable)
s - string to logthrowable - Throwable instance to logprotected void log_trace(String s)
s - string to logprotected void log_trace(String s, Throwable throwable)
s - string to logthrowable - Throwable instance to logpublic final String getName()
public final int getMinPool()
public final int getMaxPool()
public final int getMaxSize()
protected long getIdleTimeoutUnadjusted()
public long getIdleTimeout()
getIdleTimeoutMultiplier() method,
and may be overridden by sub-classes to provide idleTimeout scaling
(default of 1 for milliseconds, e.g. 1000 changes to seconds).protected float getIdleTimeoutMultiplier()
protected long getMinimumCleaningInterval()
Cleaner thread (milliseconds).Cleaner thread (milliseconds)protected long getMaximumCleaningInterval()
Cleaner thread (milliseconds).Cleaner thread (milliseconds)public final void setParameters(int maxPool,
int maxSize,
long idleTimeout)
minPool).
Any items currently in the pool will remain, subject to the new parameters.
(The hit rate counters are reset when this method is called.)maxPool - maximum number of items to be kept in poolmaxSize - maximum number of items to be createdidleTimeout - idle timeout for unused items (0 = no timeout)public final void setParameters(int minPool,
int maxPool,
int maxSize,
long idleTimeout)
minPool - minimum number of items to be kept in poolmaxPool - maximum number of items to be kept in poolmaxSize - maximum number of items to be createdidleTimeout - idle timeout for unused items (0 = no timeout)public final int getSize()
public final int getCheckedOut()
public final int getFreeCount()
public final long getRequestCount()
resetHitCounter()
method was called.resetHitCounter()
method was calledpublic final float getPoolHitRate()
public final float getPoolMissRate()
public final void resetHitCounter()
public final void setSelectionStrategy(ObjectPool.Strategy selection)
selection - selection strategyprotected Class<? extends List> getPoolClass()
List collections should be used.
(Default: java.util.ArrayList class)
For reference, pool items are checked-in to the tail end of the list.public final void flush()
public boolean equals(Object o)
public int hashCode()
public int compareTo(ObjectPool<T> pool)
equals(Object), comparing the same fields.compareTo in interface Comparable<ObjectPool<T extends Reusable>>pool - pool to compare against this instancepublic final void addObjectPoolListener(ObjectPoolListener<T> x)
x - listener to addpublic final void removeObjectPoolListener(ObjectPoolListener<T> x)
x - listener to removeCopyright © 2015. All rights reserved.