1 16 package net.sf.dozer.util.mapping.cache; 17 18 import java.util.Collection ; 19 import java.util.Map ; 20 21 import net.sf.dozer.util.mapping.stats.GlobalStatistics; 22 import net.sf.dozer.util.mapping.stats.StatisticTypeConstants; 23 import net.sf.dozer.util.mapping.stats.StatisticsManagerIF; 24 25 import org.apache.commons.collections.map.LinkedMap; 26 import org.apache.commons.lang.builder.ReflectionToStringBuilder; 27 import org.apache.commons.lang.builder.ToStringStyle; 28 29 32 public class Cache { 33 private final String name; 34 35 private long maximumSize; 36 private final Map cacheMap; 37 private long hitCount; 38 private long missCount; 39 40 public Cache(String name, long maximumSize) { 41 this.name = name; 42 this.maximumSize = maximumSize; 43 this.cacheMap = new CacheLinkedHashMap(); 44 } 45 46 public void clear() { 47 cacheMap.clear(); 48 } 49 50 public synchronized void put(CacheEntry cacheEntry) { 51 if (cacheEntry == null) { 52 throw new IllegalArgumentException ("Cache Entry cannot be null"); 53 } 54 cacheMap.put(cacheEntry.getKey(), cacheEntry); 55 if (cacheMap.size() > maximumSize) { 56 ((LinkedMap) cacheMap).remove(cacheMap.size() - 1); 58 } 59 } 60 61 public CacheEntry get(Object key) { 62 if (key == null) { 63 throw new IllegalArgumentException ("Key cannot be null"); 64 } 65 CacheEntry result = (CacheEntry) cacheMap.get(key); 66 StatisticsManagerIF statMgr = GlobalStatistics.getInstance().getStatsMgr(); 67 if (result != null) { 68 hitCount++; 69 statMgr.increment(StatisticTypeConstants.CACHE_HIT_COUNT, name); 70 } else { 71 missCount++; 72 statMgr.increment(StatisticTypeConstants.CACHE_MISS_COUNT, name); 73 } 74 return result; 75 } 76 77 public Collection getEntries() { 78 return cacheMap.values(); 79 } 80 81 public String getName() { 82 return name; 83 } 84 85 public int getSize() { 86 return cacheMap.size(); 87 } 88 89 public long getMaxSize() { 90 return maximumSize; 91 } 92 93 public void setMaxSize(long maximumSize) { 94 this.maximumSize = maximumSize; 95 } 96 97 public long getHitCount() { 98 return hitCount; 99 } 100 101 public long getMissCount() { 102 return missCount; 103 } 104 105 public String toString() { 106 return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE); 107 } 108 109 private class CacheLinkedHashMap extends LinkedMap { 110 public CacheLinkedHashMap() { 113 super(100, 0.75F); 114 } 115 } 116 117 } 118 | Popular Tags |