1 package org.roller.util; 2 import java.util.ArrayList ; 3 import java.util.Collections ; 4 import java.util.Iterator ; 5 import java.util.LinkedHashMap ; 6 import java.util.List ; 7 import java.util.Map ; 8 13 public class LRUCache2 14 { 15 private long timeout; 16 private Map cache = null; 17 private Environment environment = null; 18 19 27 public LRUCache2(int maxsize, long timeout) 28 { 29 this.environment = new DefaultEnvironment(); 30 this.timeout = timeout; 31 this.cache = new LRULinkedHashMap(maxsize); 32 } 33 34 42 public LRUCache2(Environment environment, int maxsize, long timeout) 43 { 44 this.environment = environment; 45 this.timeout = timeout; 46 this.cache = new LRULinkedHashMap(maxsize); 47 } 48 49 public synchronized void put(Object key, Object value) 50 { 51 CacheEntry entry = new CacheEntry(value, environment 52 .getCurrentTimeInMillis()); 53 cache.put(key, entry); 54 } 55 56 public Object get(Object key) 57 { 58 Object value = null; 59 CacheEntry entry = null; 60 synchronized(this) 61 { 62 entry = (CacheEntry) cache.get(key); 63 } 64 if (entry != null) 65 { 66 if (environment.getCurrentTimeInMillis() - entry.getTimeCached() < timeout) 67 { 68 value = entry.getValue(); 69 } 70 else 71 { 72 cache.remove(entry); 73 } 74 } 75 return value; 76 } 77 78 public synchronized void purge() 79 { 80 cache.clear(); 81 } 82 83 public synchronized void purge(String [] patterns) 84 { 85 List purgeList = new ArrayList (); 86 Iterator keys = cache.keySet().iterator(); 87 while (keys.hasNext()) 88 { 89 String key = (String ) keys.next(); 90 for (int i = 0; i < patterns.length; i++) 91 { 92 if (key.indexOf(patterns[i]) != -1) 93 { 94 purgeList.add(key); 95 break; 96 } 97 } 98 } 99 Iterator purgeIter = purgeList.iterator(); 100 while (purgeIter.hasNext()) 101 { 102 String key = (String ) purgeIter.next(); 103 cache.remove(key); 104 } 105 } 106 107 public int size() 108 { 109 return cache.size(); 110 } 111 public interface Environment 112 { 113 public long getCurrentTimeInMillis(); 114 } 115 public static class DefaultEnvironment implements Environment 116 { 117 public long getCurrentTimeInMillis() 118 { 119 return System.currentTimeMillis(); 120 } 121 } 122 private static class CacheEntry 123 { 124 private Object value; 125 private long timeCached = -1; 126 127 public CacheEntry(Object value, long timeCached) 128 { 129 this.timeCached = timeCached; 130 this.value = value; 131 } 132 133 public long getTimeCached() 134 { 135 return timeCached; 136 } 137 138 public Object getValue() 139 { 140 return value; 141 } 142 } 143 144 private static class LRULinkedHashMap extends LinkedHashMap 146 { 147 protected int maxsize; 148 149 public LRULinkedHashMap(int maxsize) 150 { 151 super(maxsize * 4 / 3 + 1, 0.75f, true); 152 this.maxsize = maxsize; 153 } 154 155 protected boolean removeEldestEntry(Map.Entry eldest) 156 { 157 return this.size() > this.maxsize; 158 } 159 } 160 } 161 | Popular Tags |