Sunday, January 9, 2011

Implement a simple cache with java

The class LinkedHashMap has the method removeEldestEntry() that is called before
put() method so here you can remove the eldest element from the cache.


Map mapCache = new LinkedHashMap()
{
@Override
protected boolean removeEldestEntry(Entry eldest) {
//remove after 2 hours
Calendar cal = Calendar.getInstance();
long howLongAgoInMs = System.currentTimeMillis()-eldest.getValue().lastTimeTouched;
long twoHoursInMs = 2 * 60 * 60 * 1000;
if(howLongAgoInMs > twoHoursInMs){
return true;
}
return false;
}
};

No comments:

Post a Comment