snaq.util
Class ObjectPool<T extends Reusable>

java.lang.Object
  extended by snaq.util.ObjectPool<T>
All Implemented Interfaces:
Comparable<ObjectPool>
Direct Known Subclasses:
ConnectionPool

public abstract class ObjectPool<T extends Reusable>
extends Object
implements Comparable<ObjectPool>

Base class for a pool system implementation. This class provides all the base functionality required and can be easily extended to provide pooling support for many different types of object.

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 either release or releaseAsync.

Author:
Giles Winstanley

Field Summary
protected  org.apache.commons.logging.Log logger
          Apache Commons Logging instance for writing log entries.
 
Constructor Summary
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).
 
Method Summary
 void addObjectPoolListener(ObjectPoolListener x)
          Adds an listener to the event notification list.
protected  void checkIn(T o)
          Checks an object into the pool, and notifies other threads that may be waiting for one to become available.
protected  T checkOut()
          Checks out an item from the pool.
protected  T checkOut(long timeout)
          Checks out an item from the pool.
 int compareTo(ObjectPool 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.
 long getExpiryTime()
          Deprecated. Replaced by getIdleTimeout().
 int getFreeCount()
          Returns the number of items held in the pool that are free to be checked-out.
 float getHitRate()
          Deprecated. Replaced by getPoolHitRate() which returns a unit-scaled measure instead of a percentage.
 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.
 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.
 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 for this 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 releaseAsync()
          Releases all items from the pool, and shuts the pool down.
 void releaseForcibly()
          Forcibly releases all items from the pool, and shuts the pool down.
 void removeObjectPoolListener(ObjectPoolListener 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.
protected  void setAccessFIFO()
          Sets the pool access method to FIFO (first-in, first-out: a queue).
protected  void setAccessLIFO()
          Sets the pool access method to LIFO (last-in, first-out: a stack).
protected  void setAccessRandom()
          Sets the pool access method to random (a random item is selected for check-out).
 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).
 String toString()
          Returns a descriptive string for this pool instance.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

logger

protected org.apache.commons.logging.Log logger
Apache Commons Logging instance for writing log entries.

Constructor Detail

ObjectPool

protected ObjectPool(String name,
                     int minPool,
                     int maxPool,
                     int maxSize,
                     long idleTimeout)
Creates new object pool.

Parameters:
name - pool name
minPool - minimum number of pooled objects, or 0 for none
maxPool - maximum number of pooled objects, or 0 for none
maxSize - maximum number of possible objects, or 0 for no limit
idleTimeout - idle timeout for pooled objects, or 0 for no timeout

ObjectPool

protected ObjectPool(String name,
                     int maxPool,
                     int maxSize,
                     long idleTimeout)
Creates new object pool (with minPool=0).

Parameters:
name - pool name
maxPool - maximum number of pooled objects, or 0 for none
maxSize - maximum number of possible objects, or 0 for no limit
idleTimeout - idle timeout for pooled objects, or 0 for no timeout
Method Detail

registerShutdownHook

public void registerShutdownHook()
Registers a shutdown hook for this ConnectionPoolManager instance to ensure it is released if the JVM exits


removeShutdownHook

public void removeShutdownHook()
Unregisters a registered shutdown hook for this ConnectionPoolManager instance.


toString

public String toString()
Returns a descriptive string for this pool instance.

Overrides:
toString in class Object

getParametersString

public String getParametersString()
Returns a summary string for this pool's parameters.


init

public final void init()
Initializes the pool with the default (i.e. minpool) number of items. This spawns a new thread to create them in the background, but only if there is currently no other initialization thread running. The most common use of this method is immediately after creation of a pool, to ensure it starts to populate with minPool items.


init

public final void init(int num)
Asynchronously initializes up to the specified number of items in the pool. This spawns a new thread to create them in the background. Note that the number of items specified for initialization is the final number of free items required in the pool, not the number to initialize. If free items already exist in the pool, these are included in the count.

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.


checkOut

protected final T checkOut()
                                     throws Exception
Checks out an item from the pool. If no free item is available, a new item is created unless the maximum number of items has been reached. If a free item is not valid it is removed from the pool and another is retrieved.

Returns:
item from the pool, or null if nothing available
Throws:
Exception - if there is an error creating a new object

checkOut

protected final T checkOut(long timeout)
                                     throws Exception
Checks out an item from the pool. If there is no pooled item available and the maximum number possible has not been reached, another is created. If a free item is detected as being invalid it is removed from the pool and the another is retrieved. If an item is not available and the maximum number possible has been reached, the method waits for the timeout period for one to become available by being checked in.

Parameters:
timeout - timeout value in milliseconds
Returns:
item from the pool, or null if nothing available within timeout period
Throws:
Exception - if there is an error creating a new object

checkIn

protected final void checkIn(T o)
Checks an object into the pool, and notifies other threads that may be waiting for one to become available.

Parameters:
o - object to check in

release

public final void release()
Releases all items from the pool, and shuts the pool down. If any items are still checked-out, this method waits until all items have been checked-in before returning.


isReleased

public final boolean isReleased()
Returns whether the pool has been released (and can no longer be used).


releaseAsync

public final void releaseAsync()
Releases all items from the pool, and shuts the pool down. This method returns immediately; a background thread is created to perform the release.


releaseForcibly

public final void releaseForcibly()
Forcibly releases all items from the pool, and shuts the pool down. If any items are still checked-out, this method forcibly destroys them and then returns.


preRelease

protected void preRelease()
Method to give a sub-class the opportunity to cleanup resources before the pool is officially released. This method is called as the first thing before the remaining ObjectPool release implementation.


postRelease

protected void postRelease()
Method to give a sub-class the opportunity to cleanup resources after the pool is officially released. This method is called as the last thing after the main 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.


create

protected abstract T create()
                                      throws Exception
Object creation method. This method is called when a new item needs to be created following a call to one of the check-out methods.

Throws:
Exception - if unable to create the item

isValid

protected abstract boolean isValid(T o)
Object validation method. This method is called when checking-out an item to see if it is valid for use. When overridden by the sub-class it is recommended that this method perform suitable checks to ensure the object can be used without problems.


destroy

protected abstract void destroy(T o)
Object destruction method. This method is called when an object needs to be destroyed due to pool pruning/cleaning, or final release of the pool.


setAsyncDestroy

public final void setAsyncDestroy(boolean b)
Determines whether to perform asynchronous object destruction. If set to true then each time an object is destroyed (invalid object during pool operation, or when the pool is finally released) the operation is done in a separate thread, allowing the method to return immediately. This can be useful when calling the destroy method on an object takes a long time to complete.


isAsyncDestroy

public final boolean isAsyncDestroy()
Returns whether asynchronous object destruction is enabled. (Default: false)


setLog

public void setLog(PrintWriter writer)
Sets the custom log stream. In addition to regular logging, this enables a specific PrintWriter to receive log information.

Parameters:
writer - PrintWriter to which to write log entries

getCustomLogger

public LogUtil getCustomLogger()
Returns the custom LogUtil instance being used, or null if it doesn't exist.


log_error

protected void log_error(String s)
Logging relay method (to prefix pool name).


log_error

protected void log_error(String s,
                         Throwable throwable)
Logging relay method (to prefix pool name).


log_warn

protected void log_warn(String s)
Logging relay method (to prefix pool name).


log_warn

protected void log_warn(String s,
                        Throwable throwable)
Logging relay method (to prefix pool name).


log_info

protected void log_info(String s)
Logging relay method (to prefix pool name).


log_info

protected void log_info(String s,
                        Throwable throwable)
Logging relay method (to prefix pool name).


log_debug

protected void log_debug(String s)
Logging relay method (to prefix pool name).


log_debug

protected void log_debug(String s,
                         Throwable throwable)
Logging relay method (to prefix pool name).


log_trace

protected void log_trace(String s)
Logging relay method (to prefix pool name).


log_trace

protected void log_trace(String s,
                         Throwable throwable)
Logging relay method (to prefix pool name).


getName

public final String getName()
Returns the pool name.


getMinPool

public final int getMinPool()
Returns the minimum number of items that should be kept pooled.


getMaxPool

public final int getMaxPool()
Returns the maximum number of items that can be pooled.


getMaxSize

public final int getMaxSize()
Returns the maximum number of items that can be created.


getIdleTimeoutUnadjusted

protected long getIdleTimeoutUnadjusted()
Returns the idle timeout for unused items in the pool (in milliseconds).


getIdleTimeout

public long getIdleTimeout()
Returns the idle timeout for unused items in the pool. The returned value is scaled using the pool-specific time measurement, which is determined by thegetIdleTimeoutMultiplier() method, and may be overridden by sub-classes to provide idleTimeout scaling (default of 1 for milliseconds, e.g. 1000 changes to seconds).

Returns:
getIdleTimeoutUnadjusted()/getIdleTimeoutMultiplier()

getExpiryTime

@Deprecated
public long getExpiryTime()
Deprecated. Replaced by getIdleTimeout().

Alias for getIdleTimeout().


getIdleTimeoutMultiplier

protected float getIdleTimeoutMultiplier()
Returns the multiplier for adjusting the idle timeout unit. This is a convenience method for sub-classes to override if they want to adjust the time measurement for the idleTimeout parameter. By default it returns 1.0 which denotes milliseconds. A sub-class wanting to operate with seconds would override it to return 1000, or to operate in minutes, 60000.


getMinimumCleaningInterval

protected long getMinimumCleaningInterval()
Specifies the minimum time interval between cleaning attempts of the Cleaner thread.


getMaximumCleaningInterval

protected long getMaximumCleaningInterval()
Specifies the maximum time interval between cleaning attempts of the Cleaner thread.


setParameters

public final void setParameters(int maxPool,
                                int maxSize,
                                long idleTimeout)
Sets the pooling parameters (excluding 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.)

Parameters:
maxPool - maximum number of items to be kept in pool
maxSize - maximum number of items to be created
idleTimeout - idle timeout for unused items (0 = no timeout)

setParameters

public final void setParameters(int minPool,
                                int maxPool,
                                int maxSize,
                                long idleTimeout)
Sets the pooling parameters. Any items currently in the pool will remain, subject to the new parameters. (The hit rate counters are reset when this method is called.)

Parameters:
minPool - minimum number of items to be kept in pool
maxPool - maximum number of items to be kept in pool
maxSize - maximum number of items to be created
idleTimeout - idle timeout for unused items (0 = no timeout)

getSize

public final int getSize()
Returns the total number of objects held (available and checked-out).


getCheckedOut

public final int getCheckedOut()
Returns the number of items that are currently checked-out.


getFreeCount

public final int getFreeCount()
Returns the number of items held in the pool that are free to be checked-out.


getRequestCount

public final 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.


getHitRate

@Deprecated
public final float getHitRate()
Deprecated. Replaced by getPoolHitRate() which returns a unit-scaled measure instead of a percentage.

Returns hit rate of the pool as a percentage (between 0 and 100). The hit rate is the proportion of requests for an item which result in the return of an item which is in the pool, rather than which results in the creation of a new item.


getPoolHitRate

public final float getPoolHitRate()
Returns hit rate of the pool (between 0 and 1). The hit rate is the proportion of requests for an item which result in the return of an item which is in the pool, rather than which results in the creation of a new item.


getPoolMissRate

public final float getPoolMissRate()
Returns miss rate of the pool (between 0 and 1). The miss rate is the proportion of requests for an item for which no pooled item can be retrieved.


resetHitCounter

public final void resetHitCounter()
Resets the counters for determining the pool's hit/miss rates.


setAccessFIFO

protected final void setAccessFIFO()
Sets the pool access method to FIFO (first-in, first-out: a queue).


setAccessLIFO

protected final void setAccessLIFO()
Sets the pool access method to LIFO (last-in, first-out: a stack).


setAccessRandom

protected final void setAccessRandom()
Sets the pool access method to random (a random item is selected for check-out).


getPoolClass

protected Class<? extends List> getPoolClass()
Returns the class to use for the pool collection. This can be over-ridden by a sub-class to provide a different List type for the pool, which may give performance benefits in certain situations. Only instances of List collections should be used. (Default: java.util.ArrayList class) For reference, pool items are checked-in to the tail end of the list.


flush

public final void flush()
Flushes the pool of all currently available items, emptying the pool.


equals

public boolean equals(Object o)
Indicates whether some other object is "equal to" this one. This implementation performs checks on the following fields: {name, minPool, maxPool, maxSize, idleTimeout}.

Overrides:
equals in class Object

hashCode

public int hashCode()
Returns a hash code value for the object. This implementation hashes on the pool name.

Overrides:
hashCode in class Object

compareTo

public int compareTo(ObjectPool pool)
Compares this object with the specified object for order. This implementation is consistent with the implementation of equals(Object), comparing the same fields.

Specified by:
compareTo in interface Comparable<ObjectPool>

addObjectPoolListener

public final void addObjectPoolListener(ObjectPoolListener x)
Adds an listener to the event notification list.


removeObjectPoolListener

public final void removeObjectPoolListener(ObjectPoolListener x)
Removes a listener from the event notification list.



Copyright © 2013. All Rights Reserved.