1 2 24 25 26 27 28 29 package com.lutris.util; 30 31 import java.util.Hashtable ; 32 33 49 public class LRUCache { 50 51 54 private int maxSize; 55 56 59 private int currentSize; 60 61 64 private Hashtable cache; 65 66 71 private class Node { 72 Node prev, next; 73 Object key; 74 Object item; 75 int size; 76 } 77 78 83 private Node head, tail; 84 85 97 public LRUCache(int maxSize) { 98 this.maxSize = maxSize; 99 clear(); 100 } 101 102 110 public synchronized int getSize() { 111 return currentSize; 112 } 113 114 120 public synchronized int getMaxSize() { 121 return maxSize; 122 } 123 124 134 public synchronized void add(Object key, Object item) { 135 add(key, item , 1); 136 } 137 138 151 public synchronized void add(Object key, Object item, int size) { 152 if (cache.containsKey(key)) 154 remove(key); 155 while (currentSize + size > maxSize) { 157 if (!deleteLRU()) 158 break; 159 } 160 if (currentSize + size > maxSize) 161 return; 163 Node node = new Node(); 164 node.key = key; 165 node.item = item; 166 node.size = size; 167 cache.put(key, node); 168 insertNode(node); 169 currentSize += size; 170 } 171 172 173 183 public synchronized Object get(Object key) { 184 Node node = (Node)cache.get(key); 185 if (node == null) 186 return null; 187 deleteNode(node); 188 insertNode(node); return node.item; 190 } 191 192 193 202 public synchronized Object remove(Object key) { 203 Node node = (Node)cache.remove(key); 204 if (node == null) 205 return null; 206 deleteNode(node); 207 currentSize -= node.size; 208 return node.item; 209 } 210 211 212 221 public synchronized boolean containsKey(Object key) { 222 return cache.containsKey(key); 223 } 224 225 226 229 public synchronized void clear() { 230 cache = new Hashtable (); 231 head = tail = null; 232 currentSize = 0; 233 } 234 235 236 240 private void insertNode(Node node) { 241 node.next = head; 242 node.prev = null; 243 if (head != null) 244 head.prev = node; 245 head = node; 246 if (tail == null) 247 tail = node; 248 } 249 250 251 255 private void deleteNode(Node node) { 256 if (node.prev != null) 257 node.prev.next = node.next; 258 else 259 head = node.next; 260 if (node.next != null) 261 node.next.prev = node.prev; 262 else 263 tail = node.prev; 264 } 265 266 267 272 private boolean deleteLRU() { 273 if (tail == null) 274 return false; 275 currentSize -= tail.size; 276 cache.remove(tail.key); 277 deleteNode(tail); 278 return true; 279 } 280 281 284 public synchronized String toString() { 285 StringBuffer buf = new StringBuffer (); 286 buf.append("LRU "); 287 buf.append(currentSize); 288 buf.append("/"); 289 buf.append(maxSize); 290 buf.append(" Order: "); 291 Node n = head; 292 while (n != null) { 293 buf.append(n.key); 294 if (n.next != null) 295 buf.append(", "); 296 n = n.next; 297 } 298 return buf.toString(); 299 } 300 301 302 } 303 304 | Popular Tags |