1 21 package org.jsmtpd.tools.cache; 22 23 import java.util.ArrayList ; 24 import java.util.Collections ; 25 import java.util.HashMap ; 26 import java.util.List ; 27 import java.util.Map ; 28 29 36 public class SimpleCache<Key,Value> implements ICache<Key,Value> { 37 private Map <Key,Value> cachedValues = Collections.synchronizedMap(new HashMap <Key,Value>()); 38 private List <Key> keys = Collections.synchronizedList(new ArrayList <Key>()); 39 private int cacheSize = 200; 40 41 public SimpleCache(int cacheSize) { 42 this.cacheSize=cacheSize; 43 } 44 45 public synchronized Value get(Key k) { 46 if (!keys.contains(k)) 47 return null; 48 keys.remove(k); 49 keys.add(0,k); return cachedValues.get(k); 51 } 52 53 public synchronized void cache(Key key, Value value) { 54 if (keys.size()>cacheSize) { 55 int removeSize = Math.round(cacheSize / 10); 56 for (int c=0;c<removeSize;c++) { 57 Key cKey = keys.get(keys.size()); 58 keys.remove(cKey); 59 cachedValues.remove(cKey); 60 } 61 } 62 keys.add(0,key); 63 cachedValues.put(key,value); 64 65 } 66 67 public synchronized void clear() { 68 keys.clear(); 69 cachedValues.clear(); 70 71 } 72 73 public synchronized void destroy(Key k) { 74 keys.remove(k); 75 cachedValues.remove(k); 76 } 77 78 79 public void setCacheSize(int cacheSize) { 80 this.cacheSize = cacheSize; 81 } 82 83 } 84 | Popular Tags |