Wednesday, November 21, 2007

Java TTL Cache, the Quick and Dirty Way

There are many caching systems in java. I really like some of them (especially Ian Schumacher's LRU Cache). But sometimes you just to drop a quick few lines to get something in a local cache. Here is one way of doing it:

private static Map urlItemCache = Collections.synchronizedMap(new HashMap());
private static Map urlItemCacheTtl = Collections.synchronizedMap(new HashMap());
private static final long TTL=1000*60*60;//one hour in milliseconds

public static String findItemByUrl( String url) {
String item="";
Long now=Long.valueOf(Calendar.getInstance().getTimeInMillis());

//try to get the item from the local cache
item = urlItemCache.get(url);
if ( !isEmpty(item)) {
//urlItemCacheTtl.get(url) is guaranteed to have a value, since it's added at the same time urlItemCache is.
if (now.longValue() - urlItemCacheTtl.get(url).longValue() < TTL ) {
urlItemCacheTtl.put(url, now); //see comment below
return item;
} else {
urlItemCache.remove(url);
urlItemCacheTtl.remove(url);
}
}
//not found in cache
//... do you application magic here to get the item ...
if ( !isEmpty(item) ) {
urlItemCache.put(url, item); //add to local cache
urlItemCacheTtl.put(url, now);
return item;
} //else
return null;
}