1 3 package jodd.cache; 4 5 import java.util.Map ; 6 7 15 public abstract class AbstractCacheMap implements Cache { 16 17 static class CacheObject { 18 CacheObject(Object key, Object object, long timeout) { 19 this.key = key; 20 this.cachedObject = object; 21 this.timeout = timeout; 22 this.lastAccess = System.currentTimeMillis(); 23 } 24 25 final Object key; 26 final Object cachedObject; 27 long lastAccess; int accessCount; long timeout; 31 boolean isExpired() { 32 if (timeout == 0) { 33 return false; 34 } 35 return lastAccess + timeout < System.currentTimeMillis(); 36 } 37 Object getObject() { 38 lastAccess = System.currentTimeMillis(); 39 accessCount++; 40 return cachedObject; 41 } 42 } 43 44 protected Map cacheMap; 45 46 48 protected int cacheSize = 0; 50 53 public int getCacheSize() { 54 return cacheSize; 55 } 56 57 protected long timeout = 0; 59 63 public long getCacheTimeout() { 64 return timeout; 65 } 66 67 71 protected boolean existCustomTimeout = false; 72 73 77 protected boolean isPruneExpiredActive() { 78 return (timeout != 0) || existCustomTimeout; 79 } 80 81 82 84 85 89 public synchronized void put(Object key, Object object) { 90 put(key, object, timeout); 91 } 92 93 94 98 public synchronized void put(Object key, Object object, long timeout) { 99 CacheObject co = new CacheObject(key, object, timeout); 100 if (timeout != 0) { 101 existCustomTimeout = true; 102 } 103 if (isFull()) { 104 prune(); 105 } 106 cacheMap.put(key, co); 107 } 108 109 110 112 116 public Object get(Object key) { 117 CacheObject co = (CacheObject) cacheMap.get(key); 118 if (co == null) { 119 return null; 120 } 121 if (co.isExpired() == true) { 122 remove(key); 123 return null; 124 } 125 return co.getObject(); 126 } 127 128 130 134 public abstract int prune(); 135 136 137 139 143 public boolean isFull() { 144 if (cacheSize == 0) { 145 return false; 146 } 147 return cacheMap.size() >= cacheSize; 148 } 149 150 153 public synchronized void remove(Object key) { 154 cacheMap.remove(key); 155 } 156 157 160 public synchronized void clear() { 161 cacheMap.clear(); 162 } 163 164 165 168 public int size() { 169 return cacheMap.size(); 170 } 171 } 172 | Popular Tags |