1 18 19 package org.apache.roller.util.cache; 20 21 import java.util.Collections ; 22 import java.util.Date ; 23 import java.util.HashMap ; 24 import java.util.LinkedHashMap ; 25 import java.util.Map ; 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 29 30 33 public class LRUCacheImpl implements Cache { 34 35 private static Log log = LogFactory.getLog(LRUCacheImpl.class); 36 37 private String id = null; 38 private Map cache = null; 39 40 protected double hits = 0; 42 protected double misses = 0; 43 protected double puts = 0; 44 protected double removes = 0; 45 protected Date startTime = new Date (); 46 47 48 protected LRUCacheImpl(String id) { 49 50 this.id = id; 51 this.cache = Collections.synchronizedMap(new LRULinkedHashMap(100)); 52 } 53 54 55 protected LRUCacheImpl(String id, int maxsize) { 56 57 this.id = id; 58 this.cache = Collections.synchronizedMap(new LRULinkedHashMap(maxsize)); 59 } 60 61 62 public String getId() { 63 return this.id; 64 } 65 66 67 70 public synchronized void put(String key, Object value) { 71 72 this.cache.put(key, value); 73 puts++; 74 } 75 76 77 80 public synchronized Object get(String key) { 81 82 Object obj = this.cache.get(key); 83 84 if(obj == null) { 86 misses++; 87 } else { 88 hits++; 89 } 90 91 return obj; 92 } 93 94 95 public synchronized void remove(String key) { 96 97 this.cache.remove(key); 98 removes++; 99 } 100 101 102 public synchronized void clear() { 103 104 this.cache.clear(); 105 106 hits = 0; 108 misses = 0; 109 puts = 0; 110 removes = 0; 111 startTime = new Date (); 112 } 113 114 115 public Map getStats() { 116 117 Map stats = new HashMap (); 118 stats.put("startTime", this.startTime); 119 stats.put("hits", new Double (this.hits)); 120 stats.put("misses", new Double (this.misses)); 121 stats.put("puts", new Double (this.puts)); 122 stats.put("removes", new Double (this.removes)); 123 124 if((misses - removes) > 0) { 126 double efficiency = hits / (misses + hits); 127 stats.put("efficiency", new Double (efficiency * 100)); 128 } 129 130 return stats; 131 } 132 133 134 private static class LRULinkedHashMap extends LinkedHashMap { 136 protected int maxsize; 137 138 public LRULinkedHashMap(int maxsize) { 139 super(maxsize * 4 / 3 + 1, 0.75f, true); 140 this.maxsize = maxsize; 141 } 142 143 protected boolean removeEldestEntry(Map.Entry eldest) { 144 return this.size() > this.maxsize; 145 } 146 } 147 148 } 149 | Popular Tags |