public final class IndexPool extends java.lang.Object implements java.io.Serializable
IndexPoolprovides integer index value reuse. When you create an
IndexPool, you may specify the minimum and maximum allowed values (inclusive). You retrieve the next available value using
nextIndex()and return values to the pool with
returnIndex(int). When the pool is exhausted,
IllegalStateException. The application is responsible for returning unused indices to the pool by calling
returnIndex(int). The application is also responsible for making sure that
returnIndex(int)calls contain unique indicies and that the same index does not appear in the pool multiple times.
IndexPool uses both an
AtomicInteger and a
ConcurrentLinkedDeque (as a stack) to track available
nextIndex() is called, it first checks
if the index stack is empty. If it is empty, then
AtomicInteger.getAndIncrement() is called to get the
next unused index. If the returned value is > than the
maximum allowed index, then
exception is thrown. If the index stack is not empty, then
the an index is popped off the stack and returned. The idea
behind this technique is to continually use the same indices
in the hopes this improves processor cache hits.
IndexPool has no memory between application
executions. If you need to persist index values between
synchronized. It is safe for multiple threads to access the
IndexPoool instance without synchronizing.
|Constructor and Description|
Creates a pool with the default size.
Creates a pool with the specified minimum and maximum indicies (inclusive).
|Modifier and Type||Method and Description|
Returns the pool's maximum index.
Returns the pool's minimum index.
Returns the next available index.
Resets the index pool to its initial state.
Puts an index back into the pool for reuse.
Returns a textual representation of this index pool.
The default settings are:
public IndexPool(int minIndex, int maxIndex) throws java.lang.IllegalArgumentException
minIndex- the minimum index (
nextIndex()will return this value first.)
maxIndex- the maximum index (inclusive).
minIndexis <= zero.
maxIndexis <= zero.
public java.lang.String toString()
public int minIndex()
public int maxIndex()
public int nextIndex() throws java.lang.IllegalStateException
java.lang.IllegalStateException- if all indices are in use and the pool is exhausted. This may be due to a failure to return unused indicies to the pool.
public void returnIndex(int index) throws java.lang.IndexOutOfBoundsException
Note: this method does not prevent returning the same index to the pool multiple times. It is the caller's responsibility to make sure that an index appears only once in the pool.
index- Put this index back in the pool.
indexis less than the minimum index value or greater than or equal to the maximum index value.
public void reset()