1 17 18 19 20 package org.apache.lenya.util; 21 22 import java.util.Date ; 23 import java.util.HashMap ; 24 import java.util.SortedMap ; 25 import java.util.TreeMap ; 26 27 import org.apache.log4j.Category; 28 29 32 public class CacheMap extends HashMap { 33 34 private static final Category log = Category.getInstance(CacheMap.class); 35 36 40 public CacheMap(int capacity) { 41 assert capacity > -1; 42 this.capacity = capacity; 43 } 44 45 private int capacity; 46 private SortedMap timeToKey = new TreeMap (); 47 48 51 public Object put(Object key, Object value) { 52 53 if (size() == capacity) { 54 Object oldestKey = timeToKey.get(timeToKey.firstKey()); 55 remove(oldestKey); 56 if (log.isDebugEnabled()) { 57 log.debug("Clearing cache"); 58 } 59 } 60 timeToKey.put(new Date (), key); 61 return super.put(key, value); 62 } 63 64 65 66 69 public Object get(Object key) { 70 Object result = super.get(key); 71 if (log.isDebugEnabled()) { 72 if (result != null) { 73 log.debug("Using cached object for key [" + key + "]"); 74 } 75 else { 76 log.debug("No cached object for key [" + key + "]"); 77 } 78 } 79 return result; 80 } 81 82 } 83 | Popular Tags |