Rakesh API

org.rakeshv.utils
Class ObjectCache<K,V>

java.lang.Object
  extended by org.rakeshv.utils.ObjectCache<K,V>

public class ObjectCache<K,V>
extends java.lang.Object

A simple decorator around a LinkedHashMap and DynamicCache that can be used to cache object instances.

Note 1: Key's added to the internal cache must have a proper hashCode() implementation since they are stored in a Map.

Note 2: Instances of this class will not be garbage collected if your reference to it goes out of scope. You must invoke the release() method if you wish to consign instances of this class to the garbage collector.

Note 3: You must set the system property org.rakeshv.utils.ObjectCache.totalItems to the value you desire if you wish to restrict the number of items that are cached if you use the ObjectCache() default constructor. The property must be specified prior to creating a new instance of this class. See sample code provided for examples on how to specify the property.

Note 4: This class uses a LRU model for managing the cache by default. When new instances are requested after the cache size has grown to the configured total size, new instances are added to the cache, and the least accessed instances are removed.

The following code shows sample usage of the cache:

  import org.rakeshv.utils.DataStructure;
  import org.rakeshv.utils.ObjectCache;

    ...

    // Create a dynamic cache that uses SoftReferences to dynamically
    // control cache size.  This works only if the system property
    // for default cache size is not set.
    // Set the automatic garbage collected value mapping removal to
    // run every 5 minutes rather than the default 10 minutes
    // (specified in seconds)
    System.getProperties().setProperty( 
        "org.rakeshv.utils.DynamicCache.cleanInterval", "300" );
    ObjectCache<Date, MyObject> dynamic = new ObjectCache<Date, MyObject>()

    // Create a LRU with specified size
    ObjectCache<Date, MyObject> lru = new ObjectCache<Date, MyObject>( 50000 );

    // Create a FIFO of specified size
    ObjectCache<Date, MyObject> fifo = new ObjectCache<Date, MyObject>( 50000, DataStructure.FIFO );

    // Get the statistics for cache usage
    System.out.format( "lru statistics: %s%n", lru.getStatistics() );
    System.out.format( "Total fifo requests: %d%n", fifo.getStatistics().getTotalRequests() );
    System.out.format( "Total successful fifo requests: %d%n", fifo.getStatistics().getSuccessfulRequests() );
    System.out.format( "Total entries removed from fifo: %d%n", fifo.getStatistics().getTotalRemoved() );
 

Copyright 2004-2006 Rakesh Vidyadharan

Version:
$Id: ObjectCache.java,v 1.17 2006/03/24 18:24:11 rakesh Exp $
Author:
Rakesh Vidyadharan 2004 September 1

Field Summary
private  Map<K,V> cache
          The Map that is used to store the object instances that are to be shared.
private  java.lang.String key
          The key used to store instances of this class.
private  java.util.Random random
          A random number generator used to ensure that key values generated are unique.
static java.lang.String TOTAL_ITEMS_PROPERTY
          The System property name used to fetch user defined maximum number of items to cache.
private  int totalItems
          The maximum number of items to hold in the cache.
 
Constructor Summary
ObjectCache()
          Default constructor.
ObjectCache(int size)
          Create a new instance with the specified size for the cache.
ObjectCache(int size, int cacheType)
          Create a new instance with the specified size for the cache and the datastructure to use.
 
Method Summary
 void clear()
          Remove all the entries from cache.
 boolean containsKey(java.lang.Object key)
          Returns true if the cache contains a mapping for the specified key.
 boolean containsValue(java.lang.Object value)
          Returns true if the cache maps one or more keys to the specified value.
 boolean equals(java.lang.Object object)
          Compares the specified object with this instance for equality.
 java.lang.Object get(java.lang.Object key)
          Returns the value to which the cache maps the specified key.
 Map.Statistics getStatistics()
          Returns a LinkedHashMap.Statistics instance that contains information about cache usage.
 int getTotalItems()
          Returns totalItems.
 int hashCode()
          Returns the hash code value for cache.
private  void init()
          Initialise the class instance
private  void initCache(int cacheType)
          Initialise the cache.
 boolean isEmpty()
          Returns true if cache contains no key-value mappings.
 java.util.Set<K> keySet()
          Returns a set view of the keys contained in cache.
 void put(K key, V value)
          Add the specified key-value pair to cache.
 void release()
          Make this instance of the class eligible for garbage collection.
 java.lang.Object remove(java.lang.Object key)
          Removes the mapping for this key from the cache if it is present.
 void setTotalItems(int totalItems)
          Set/change totalItems.
 int size()
          Return the number of objects stored in cache.
 java.lang.String toString()
          Returns a string representation of this object.
 java.util.Collection<V> values()
          Returns a collection view of the values contained in cache.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

TOTAL_ITEMS_PROPERTY

public static final java.lang.String TOTAL_ITEMS_PROPERTY
The System property name used to fetch user defined maximum number of items to cache.

See Also:
Constant Field Values

cache

private Map<K,V> cache
The Map that is used to store the object instances that are to be shared.


random

private java.util.Random random
A random number generator used to ensure that key values generated are unique.


key

private java.lang.String key
The key used to store instances of this class.


totalItems

private int totalItems
The maximum number of items to hold in the cache. This value will default to Integer.MAX_VALUE if the system property TOTAL_ITEMS_PROPERTY is not specified.

Constructor Detail

ObjectCache

public ObjectCache()
Default constructor. Initialises the instance variables.

See Also:
SharedObject.fetchTotalItemsProperty(java.lang.String), init()

ObjectCache

public ObjectCache(int size)
Create a new instance with the specified size for the cache.

Parameters:
size - The maximum number of objects to store in the cache.
See Also:
init(), initCache( int )

ObjectCache

public ObjectCache(int size,
                   int cacheType)
Create a new instance with the specified size for the cache and the datastructure to use.

The valid value for cacheType are:

  1. DataStructure.FIFO
  2. DataStructure.LRU

Parameters:
size - The maximum number of shared objects to store in the cache.
See Also:
init(), initCache( int )
Method Detail

initCache

private void initCache(int cacheType)
Initialise the cache. The cache is initialised with the appropriate cacheType.

The valid value for cacheType are:

  1. DataStructure.FIFO
  2. DataStructure.LRU
  3. DataStructure.DYNAMIC

If an invalid value is specified for cacheType then a LRU datastructure is used.

Parameters:
cacheType - The type of datastructure to use to manage the cache.

init

private void init()
Initialise the class instance


release

public void release()
Make this instance of the class eligible for garbage collection. The instance will be eligible for garbage collection after this method has been invoked, and any references client code has to this object go out of scope.


hashCode

public int hashCode()
Returns the hash code value for cache. The hash code of a map is defined to be the sum of the hashCodes of each entry in the map's entrySet view. This ensures that t1.equals(t2) implies that t1.hashCode()==t2.hashCode() for any two maps t1 and t2, as required by the general contract of Object.hashCode.

Overrides:
hashCode in class java.lang.Object

equals

public boolean equals(java.lang.Object object)
Compares the specified object with this instance for equality. Returns true if the given object is also a ObjectCache and the two cache objects represent the same mappings. More formally, two maps t1 and t2 represent the same mappings if t1.entrySet().equals(t2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Overrides:
equals in class java.lang.Object

toString

public java.lang.String toString()
Returns a string representation of this object. Returns some useful information about this class and the data it holds.

Overrides:
toString in class java.lang.Object
Returns:
String The string representation.

put

public void put(K key,
                V value)
         throws java.lang.IllegalArgumentException
Add the specified key-value pair to cache. If a restriction was specified for totalItems, then the earliest key-value pair is removed and the new pair added if the size of the cache exceeds totalItems.

Parameters:
key - Key with which the specified value is to be associated.
value - Value to be associated with the specified key.
Throws:
java.lang.IllegalArgumentException - If a null value was specified for the key.

keySet

public java.util.Set<K> keySet()
Returns a set view of the keys contained in cache. To preserve encapsulation of the cache, the set is disconnected from the cache.

Returns:
A set of the keys contained in the cache.

values

public java.util.Collection<V> values()
Returns a collection view of the values contained in cache. To preserve encapsulation of the cache, the collection is u disconnected from the cache.

Returns:
A collection of the keys contained in the cache.

isEmpty

public boolean isEmpty()
Returns true if cache contains no key-value mappings.

Returns:
true if the cache contains no key-value mappings.

containsKey

public boolean containsKey(java.lang.Object key)
Returns true if the cache contains a mapping for the specified key. More formally, returns true if and only if the cache contains at a mapping for a key k such that (key==null ? k==null : key.equals(k)). (There can be at most one such mapping.)

Parameters:
key - Key whose presence in the cache is to be tested.
Returns:
true if the cache contains a mapping for the specified key.

containsValue

public boolean containsValue(java.lang.Object value)
Returns true if the cache maps one or more keys to the specified value. More formally, returns true if and only if the cache contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface.

Parameters:
value - Value whose presence in the cache is to be tested.
Returns:
true if the cache maps one or more keys to the specified value.

get

public java.lang.Object get(java.lang.Object key)
Returns the value to which the cache maps the specified key. Returns null if the map contains no mapping for this key. A return value of null does not necessarily indicate that the map contains no mapping for the key; it is also possible that the map explicitly maps the key to null. The containsKey( Object ) operation may be used to distinguish these two cases.

More formally, if the cache contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

Parameters:
key - Key whose associated value is to be returned.
Returns:
value to which the cache maps the specified key, or null if the map contains no mapping for this key.

size

public int size()
Return the number of objects stored in cache.

Returns:
int The number of cached objects.

clear

public void clear()
Remove all the entries from cache. This operation will reset all LinkedHashMap.Statistics associated with the cache.


remove

public java.lang.Object remove(java.lang.Object key)
Removes the mapping for this key from the cache if it is present. More formally, if the cache contains a mapping from key k to value v such that (key==null ? k==null : key.equals(k)), that mapping is removed. (The map can contain at most one such mapping.)

Returns the value to which the map previously associated the key, or null if the map contained no mapping for this key. (A null return can also indicate that the map previously associated null with the specified key.) The map will not contain a mapping for the specified key once the call returns.

Parameters:
key - Key whose mapping is to be removed from the map.
Returns:
Previous value associated with specified key, or null if there was no mapping for key.

getTotalItems

public final int getTotalItems()
Returns totalItems.

Returns:
int The value/reference of/to totalItems.

setTotalItems

public final void setTotalItems(int totalItems)
Set/change totalItems. This can be used to modify the cache size dynamically.

Parameters:
totalItems - The value to set.

getStatistics

public final Map.Statistics getStatistics()
Returns a LinkedHashMap.Statistics instance that contains information about cache usage.

Returns:
Statistics The value/reference of/to statistics.

Rakesh API

Copyright © 2002-2005 - Rakesh Vidyadharan