Nothing is forever. If you have a program that is short-lived compared to the mean time between change of the data being cached, then a LRU cache will be more than adequate. If the program is an application server and could be left running for days, weeks or even months -
then there's a good chance that the data being cached will need to be changed. Enter the time sensitive cache.
A time sensitive cache can be created with a special constructor or built from a LRU cache with the
ageingCache method. In both cases you provide the number of minutes cached items are useful for (as either a property or a number) and a flag set to true to fix the expiry time.
// Once 50 elements are cached the least recently accessed will be discarded.
Cache cache = new Cache( 50);
// Or if the items are 6 hours old
cache.ageingCache( 6 * 60, true);
Every 30 seconds the cache daemon checks all caches for expired entries and removes them. If you attempt to retrieve a cached item after it expires it will be cleared then. It's the responsibility of the calling code to reload an expired item; as this is exactly the same as opening it the first time, no additional code should be necessary.
byte[] buffer = cache.get( fileName);
if (buffer == null)
buffer = readFile( fileName);
If you need for an entry to be reloaded early, call expire(). If you want to clear the entire cache, just create a new instance and let the old clean itself up. Since time sensitive caches rarely hold Closeable there should be few concerns about locked entries.
Time sensitive caches are typically used to store data that's needed regularly and is more expensive to retrieve from the original source. Two common examples include files and reference data in a database.
Next week will talk about how to use Cache for time-limiting caches. This is the same technology but for a completely different application.
--
Posted by Paul Marrington to Adept Open Source Library at 9/26/2005 01:26:00 PM