com.marringtons.util
Class Cache

java.lang.Object
  extended bycom.marringtons.util.Cache

public class Cache
extends Object

This is a generic caching system allowing LRU, time sensitive, time limited and pooling caches.

Usages:

Items added to a cache can have an interface of Closeable. If they do they are closed when they are removed. The lock is also effective - and in-use items cannot be removed from the cache. Items added that are not Closeable will be removed with the rules above - regardless on whether they have been unlocked. Attempting to clean locked items indicates a problem - usually a resource leak.
 Cache fileCache = new cache( 100);	// If more than 10, close oldest
 fileCache.ageingCache( 12 * 60, true); // files will be reloaded every 12 hours

 Cache sessionCache = new cache( 1000); // sessions will expire, not get pushed out because there are too many
 sessionCache.ageingCache( 20, false); // sessions expire after 20 minutes
 if (! sessionCache.full()) sessionCache.add( key, session);
 sessionCache.setExpiry( 60);
 if (logout()) sessionCache.expire( key);

 Cache zipCache = new cache( "zip.cache.size", 10);	// get size from system properties file (or default if no property)
 ZipFile zipFile = (ZipFile) zipCache.get( zipFileName);
 if (zipFile == null)
 	{
 		zipFile = openZipFile( zipFileName);
 		cache.add( zipFileName, zipFile);
 	}
 use( zipFile);
 finally { cache.unlock( zipFileName); }
 
 Cache pool = new cache( 100);	// up to 100 pooled connections can be open instanteously
 pool.ageingCache( 5, false);	// Any connection unused for 5 minutes will be closed.
 //pool.ageingCache( 60, true); // connections will be closed and reopened if over 1 hours old
 Connection connection = pool.get();	// get the LRU entry from the pool
 if (connection == null) pool.add( new Connection());	// no more, create a new one
 use( connection);
 cache.unlock( connection);
 

Author:
Paul Marrington

Constructor Summary
Cache(int maximumWeight)
          Initialise cache with maximum number of entries before the oldest are cleared.
Cache(String property, int maximumSize)
          Initialise cache with maximum number of entries from the properties file before the oldest are cleared.
Cache(String property, int expiryMinutes, boolean fixedExpiryTime)
          Initialise time-sensitive cache with the default amount of time before an entry expires.
 
Method Summary
 void add(Closeable object)
          For pools - a special sort of cache where items are retrieved on LRU basis.
 boolean add(int key, Closeable object)
          Add an object to the cache with an integer key.
 boolean add(int key, Object object)
          Add an object to the cache with an integer key.
 boolean add(Object key, Closeable object)
          Add an object to the cache.
 boolean add(Object key, Object object)
          Add an object to the cache.
 void ageingCache(int expiryMinutes, boolean fixedExpiryTime)
          Call to create an ageing cache.
 int clear()
          Delete all entries in the cache and remove them.
 boolean close()
          Delete all entries from cache then close cache so that all resources can be released.
static boolean closeAll()
          If some caches hold critical data that needs to be preserved, either close the specific cache with close() or close all caches before stopping the program.
 boolean delete(Object key)
          Delete and remove an object from the cache.
 boolean exists(Object key)
          Check to see if an item exists in the cache.
 boolean expire(Object key)
          Forced delete for ageing caches - removes even if not expired.
 boolean full()
          See if the cache is full.
 Object get()
          Retrieve the most used item from the cache (pooling).
 Object get(Object key)
          Retrieve an object from the cache.
 boolean isAgeingCache()
          See if cache items can expire due to age as well as on LRU basis.
 void setCacheSize(int size)
          Reset the maximum number of entries in the cache.
 boolean setExpiry(Object key, int minutes)
          Set the expiry time for an entry.
 int size()
          Return the number of active items currently in the cache pool.
 boolean unlock(Object key)
          Unlock an object previously retrieved by get().
 boolean unlockQuietly(Object key)
          Unlock an object previously retrieved by get().
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Cache

public Cache(String property,
             int maximumSize)
Initialise cache with maximum number of entries from the properties file before the oldest are cleared.

Parameters:
property - an integer system property entry holding the size when it starts flushing.
maximumSize - size to make cache if not in properties file

Cache

public Cache(String property,
             int expiryMinutes,
             boolean fixedExpiryTime)
Initialise time-sensitive cache with the default amount of time before an entry expires.

Parameters:
property - an integer system property entry holding the size when it starts flushing.
expiryMinutes - time before cache item expires and is removed.
fixedExpiryTime - true means time from cache entry, false for time from last retrieval.

Cache

public Cache(int maximumWeight)
Initialise cache with maximum number of entries before the oldest are cleared.

Parameters:
maximumWeight - the size when the cache starts flushing.
Method Detail

ageingCache

public void ageingCache(int expiryMinutes,
                        boolean fixedExpiryTime)
Call to create an ageing cache. Items in this cache can be thrown out for being too old as well as having too many. Used for sessions, but also to cause cache items to be reloaded daily if they change infrequently.

Parameters:
expiryMinutes - time after creation/access that an item is considered stain
fixedExpiryTime - true to make expiry happen at that time after creation. Otherwise expiry will be reset every time the item is unlocked (not quietly).

isAgeingCache

public boolean isAgeingCache()
See if cache items can expire due to age as well as on LRU basis.

Returns:
true if items can go past their use-by.

exists

public boolean exists(Object key)
Check to see if an item exists in the cache.

Parameters:
key - of item to look for in the cache.
Returns:
boolean

get

public Object get()
Retrieve the most used item from the cache (pooling). Entry must be unlocked as soon as you have finished with it. It will then be returned to the pool. Not for transient (not closeable) items.

Returns:
next most used item from the cache or null if cache is empty.

get

public Object get(Object key)
Retrieve an object from the cache. Entry must be unlocked as soon as you have finished with it.

Parameters:
key - of cached item to retrieve.
Returns:
specified cached item or null if it does not exist.

unlock

public boolean unlock(Object key)
Unlock an object previously retrieved by get(). A locked object will never be deleted from the cache. The item being unlocked is now MRU.

Parameters:
key - of cached item to unlock.
Returns:
true if the item was not in use and so could be unlocked.

unlockQuietly

public boolean unlockQuietly(Object key)
Unlock an object previously retrieved by get(). A locked object will never be deleted from the cache. The item is not made MRU (i.e. it was never used after retrieval).

Parameters:
key - of cached item to unlock.
Returns:
true if the item was not in use and so could be unlocked.

full

public boolean full()
See if the cache is full. Use for cases where you don't want the oldest member to be flushed. This would be uses such as sessions where you should not throw off an old session just because you want to create another and there is not enough room.
 if (! cache.full()) cache.add( key, item);
 

Returns:
true if the cache is full.

add

public void add(Closeable object)
For pools - a special sort of cache where items are retrieved on LRU basis. Add an object to the pool. Only called if there are no unused items in the pool.

Parameters:
object - to add

add

public boolean add(Object key,
                   Closeable object)
Add an object to the cache. Each object has the same weight (1). If the object exists, set it to most recently used. That way clients can use add after a getQuietly without caring if they retrieved or created the entry.

Parameters:
key - cache access key for object
object - to add
Returns:
true to add, false if it already exists (lock updated)

add

public boolean add(Object key,
                   Object object)
Add an object to the cache. Each object has the same weight (1). If the object exists, set it to most recently used. That way clients can use add after a getQuietly without caring if they retrieved or created the entry.

Parameters:
key - cache access key for object
object - to add
Returns:
true to add, false if it already exists (lock updated)

add

public boolean add(int key,
                   Closeable object)
Add an object to the cache with an integer key. If the object exists, set it to most recently used. That way clients can use add after a getQuietly without caring if they retrieved or created the entry.

Parameters:
key - cache access key for object
object - to add
Returns:
true to add, false if it already exists (lock updated)

add

public boolean add(int key,
                   Object object)
Add an object to the cache with an integer key. If the object exists, set it to most recently used. That way clients can use add after a getQuietly without caring if they retrieved or created the entry.

Parameters:
key - cache access key for object
object - to add
Returns:
true to add, false if it already exists (lock updated)

setExpiry

public boolean setExpiry(Object key,
                         int minutes)
Set the expiry time for an entry. If not used the default expiry time from when the cache was created is used. This method is used by session caches where user sessions have different expiry values.

Parameters:
key - to finding the entry.
minutes - after which the item is considered expired
Returns:
true if the entry exists

delete

public boolean delete(Object key)
Delete and remove an object from the cache. Reduce the weight of the cache accordingly.

Parameters:
key - of cache entry to delete.
Returns:
true if there was an entry to delete.

expire

public boolean expire(Object key)
Forced delete for ageing caches - removes even if not expired.

Parameters:
key - of cached entry to expure and delete.
Returns:
true if there was an entry to delete.

clear

public int clear()
Delete all entries in the cache and remove them.

Returns:
number of locked items that could not be closed

close

public boolean close()
Delete all entries from cache then close cache so that all resources can be released.

Returns:
true if cache could be closed - false if some items refused to be closed.

closeAll

public static boolean closeAll()
If some caches hold critical data that needs to be preserved, either close the specific cache with close() or close all caches before stopping the program.
 public static void main( String[] args )
   {
    	try
       {
 					// ...
       }
     finally
       { Cache.closeAll(); }
   }
 

Returns:
true if all cache entries were not locked.

setCacheSize

public void setCacheSize(int size)
Reset the maximum number of entries in the cache. Use to fix chicken-and-egg problem where the cache has to be created before it's final size is known. Only example of this is the zipFileCache in FileReader. Note that the size can be made larger - not smaller.

Parameters:
size - to set the cache to.

size

public int size()
Return the number of active items currently in the cache pool.

Returns:
number of items in the pool


Copyright © 2005 Paul Marrington http://library.marringtons.com