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

Method Summary
 void addObjectPoolListener(ObjectPoolListener x)
          Adds an listener to the event notification list.
 int compareTo(ObjectPool pool)
          Compares this object with the specified object for order.
 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.
 int getMaxPool()
          Returns the maximum number of items that can be pooled.
 int getMaxSize()
          Returns the maximum number of items that can be created.
 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.
 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).
 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()
          Deregisters 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).
 String toString()
          Returns a descriptive string for this pool instance.
 
Methods inherited from class java.lang.Object
getClass, notify, notifyAll, wait, wait, wait
 

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()
Deregisters 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.


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.


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.


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.


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().


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.


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.