Rakesh API

org.rakeshv.utils
Class SharedObject<T>

java.lang.Object
  extended by org.rakeshv.utils.SharedObject<T>

public class SharedObject<T>
extends java.lang.Object

A decorator around a Map that can be used to share object instances. In addition to sharing instances, this class also enforces type safety by allowing only one class type per instance of this class.

Note 1: Objects 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.SharedObject.totalItems to the value you desire if you wish to restrict the number of items that are cached if you use the SharedObject() 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 system property, new instances are added to the cache, and the least requested instances are removed.

The following test program shows a way of using this class:

 
                import org.rakeshv.utils.SharedObject;
                import java.util.Date;
                
                public class test
                {
                  public static void main( String[] args )
                  {
                    System.setProperty( SharedObject.TOTAL_ITEMS_PROPERTY, "1000" );
                    SharedObject cache = new SharedObject();
                
                    Date one = new Date();
                    Date two = new Date();
                    two.setTime( two.getTime() + 1000 );
                    Date three = new Date();
                    three.setTime( three.getTime() + 2000 );
                
                    cache.getSharedObject( one );
                    cache.getSharedObject( two );
                    cache.getSharedObject( three );
                
                    if ( one == cache.getSharedObject( one ) )
                    {
                      System.out.println( "one one good" );
                    }
                    else
                    {
                      System.out.println( "one one bad" );
                    }
                
                    Date four = new Date();
                    four.setTime( one.getTime() );
                    if ( one == cache.getSharedObject( four ) )
                    {
                      System.out.println( "one four good" );
                    }
                    else
                    {
                      System.out.println( "one four bad" );
                    }
                
                    if ( one == cache.getSharedObject( two ) )
                    {
                      System.out.println( "one two good" );
                    }
                    else
                    {
                      System.out.println( "one two bad" );
                    }

                    cache.release();
                  }
                }
 

Compiling and running the test class outputs the following:

                one one good
                one four good
                one two bad
 

You can also specify the system property for cache size as a JVM parameter using:

    java -cp rvfilters.jar:. -Dorg.rakeshv.utils.SharedObject.totalItems=1000 test
 

Copyright 2004-2006 Rakesh Vidyadharan

Version:
$Id: SharedObject.java,v 1.16 2006/03/14 22:55:36 rakesh Exp $
Author:
Rakesh Vidyadharan 2004 August 22

Field Summary
private  Map<T,T> cache
          A 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.
private  java.lang.Class type
          The type of the objects stored in the cache.
 
Constructor Summary
SharedObject()
          Default constructor.
SharedObject(int size)
          Create a new instance with the specified size for the cache.
SharedObject(int size, int cacheType)
          Create a new instance with the specified size for the cache and the datastructure to use.
 
Method Summary
private  void addObject(T object)
          Add the specified object to cache.
 void clear()
          Remove all the entries from cache.
 boolean contains(java.lang.Object key)
          Returns true if cache contains a mapping for the specified key.
 boolean equals(java.lang.Object object)
          Compares the specified object with this instance for equality.
(package private) static int fetchTotalItemsProperty(java.lang.String property)
          Fetch the system property for totalItems.
 T getSharedObject(T object)
          Return the shared instance for the specified object.
 int getTotalItems()
          Returns totalItems.
 java.lang.Class getType()
          Returns type.
 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<T> keySet()
          Returns a set view of the keys contained in cache.
 void release()
          Make this instance of the class eligible for garbage collection.
 void remove(java.lang.Object key)
          Removes the mapping for this key from cache if it is present.
 int size()
          Return the number of objects stored in cache.
 java.lang.String toString()
          Returns a string representation of this object.
 
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. "org.rakeshv.utils.SharedObject.totalItems"

See Also:
Constant Field Values

cache

private Map<T,T> cache
A Map that is used to store the object instances that are to be shared.


type

private java.lang.Class type
The type of the objects stored in the cache.


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

SharedObject

public SharedObject()
Default constructor. Initialises the instance variables. Uses a LRU implementation to manage the cache size, if a maximum size was specified using the TOTAL_ITEMS_PROPERTY system property. Otherwise it uses a DynamicCache to manage the cache.

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

SharedObject

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

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

SharedObject

public SharedObject(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
  3. DataStructure.DYNAMIC

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

getSharedObject

public T getSharedObject(T object)
                  throws java.lang.ClassCastException,
                         java.lang.IllegalArgumentException
Return the shared instance for the specified object. If the specified object is not found in the cache, then it is added to the cache. If the cache size is greater than totalItems, then the specified object is added to the cache and an older object removed.

On first invocation of the method it sets type with the type of the specified object.

Parameters:
object - The object that is to be added to the cache if required.
Throws:
java.lang.ClassCastException - If the specified object is not of the same type as the objects stored in the cache.
java.lang.IllegalArgumentException - If a null value was specified for the object.

initCache

private void initCache(int cacheType)
Initialise the cache. The cache is initialised based upon the cacheType parameter specified.

The valid value for cacheType are:

  1. DataStructure.FIFO_IMPLEMENTATION
  2. DataStructure.LRU_IMPLEMENTATION

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


addObject

private void addObject(T object)
Add the specified object to cache. If a restriction was specified for totalItems, then the object is added to the FIFO and the earliest object removed.

Parameters:
object - The object to be added to the cache.

clear

public void clear()
Remove all the entries from cache.


fetchTotalItemsProperty

static final int fetchTotalItemsProperty(java.lang.String property)
Fetch the system property for totalItems.

Parameters:
property - The name of the system property to fetch.

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 SharedObject with the same type 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.

getType

public final java.lang.Class getType()
Returns type.

Returns:
Class The value/reference of/to type.

getTotalItems

public final int getTotalItems()
Returns totalItems.

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

keySet

public java.util.Set<T> 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.

isEmpty

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

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

contains

public boolean contains(java.lang.Object key)
Returns true if 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.

size

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

Returns:
int The number of cached objects.

remove

public void remove(java.lang.Object key)
Removes the mapping for this key from 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.)

Parameters:
key - Key whose mapping is to be removed from the map.

Rakesh API

Copyright © 2002-2005 - Rakesh Vidyadharan