1 package org.shiftone.cache.util; 2 3 4 5 import org.shiftone.cache.util.reaper.ReapableCache; 6 7 8 15 public abstract class AbstractPolicyCache implements ReapableCache 16 { 17 18 private static final double MIN_PCT_FREE = 1.0; 19 private static final int SHRINK_MULT = 2; 20 public static final int SHRINK_DIV = 3; 21 private final String name; 22 private final int maxSize; 23 private final long timeoutMilliSeconds; 24 25 protected AbstractPolicyCache(String name, long timeoutMilliSeconds, int maxSize) 26 { 27 28 this.name = name; 29 this.timeoutMilliSeconds = timeoutMilliSeconds; 30 this.maxSize = maxSize; 31 } 32 33 34 public final void addObject(Object userKey, Object cacheObject) 35 { 36 37 CacheNode node; 38 39 40 41 node = findNodeByKey(userKey); 42 43 if (node != null) 44 { 45 46 node.setValue(cacheObject); 50 revalueNode(node); 51 } 52 else 53 { 54 shrinkToSize(getMaxSize() - 1); 55 createNode(userKey, cacheObject); 56 } 57 58 removeExpiredElements(); 59 60 } 62 63 64 public final Object getObject(Object key) 65 { 66 67 Object value = null; 68 CacheNode node; 69 70 removeExpiredElements(); 71 72 node = findNodeByKey(key); 73 74 if (node == null) 75 { 76 ; } 78 else if (node.isExpired()) 79 { 80 delete(node); 81 } 82 else if (node != null) 83 { 84 revalueNode(node); 85 86 value = node.getValue(); 87 } 88 89 return value; 90 } 91 92 93 public final void remove(Object key) 94 { 95 96 CacheNode node = findNodeByKey(key); 97 98 if (node != null) 99 { 100 delete(node); 101 } 102 103 removeExpiredElements(); 104 } 105 106 107 protected String getName() 108 { 109 return name; 110 } 111 112 113 protected final int getMaxSize() 114 { 115 return this.maxSize; 116 } 117 118 119 protected final long getTimeoutMilliSeconds() 120 { 121 return this.timeoutMilliSeconds; 122 } 123 124 125 129 private final void shrinkToSize(int desiredSize) 130 { 131 132 while (size() > desiredSize) 133 { 134 135 removeLeastValuableNode(); 137 } 138 } 139 140 141 147 public void clear() 148 { 149 shrinkToSize(0); 150 } 151 152 153 156 private final void checkFreeMemory() 157 { 158 159 178 } 179 180 181 184 abstract protected CacheNode findNodeByKey(Object key); 185 186 187 191 abstract protected void revalueNode(CacheNode node); 192 193 194 197 abstract protected void delete(CacheNode node); 198 199 200 208 abstract protected void removeLeastValuableNode(); 209 210 211 214 abstract public void removeExpiredElements(); 215 216 217 220 abstract protected CacheNode createNode(Object userKey, Object cacheObject); 221 222 223 private static String shortName(Class klass) 224 { 225 226 String className = klass.getName(); 227 int lastDot = className.lastIndexOf('.'); 228 229 if (lastDot != -1) 230 { 231 className = className.substring(lastDot + 1); 232 } 233 234 return className; 235 } 236 237 238 public String toString() 239 { 240 return shortName(getClass()) + "(" + getName() + "," + getTimeoutMilliSeconds() + "," + getMaxSize() + ")"; 241 } 242 } 243 | Popular Tags |