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