01: package ri.cache.eviction;
02:
03: import javax.cache.Cache;
04: import javax.cache.CacheEntry;
05: import java.util.HashMap;
06: import java.util.Map;
07:
08: public class LRUChainEvictionStrategy<K, V> extends
09: AbstractEvictionStrategy<K, V> {
10:
11: protected final Entry header = new Entry(null, null, -1L);
12:
13: public LRUChainEvictionStrategy() {
14: header.next = header.previous = header;
15: }
16:
17: public CacheEntry<K, V> createEntry(K key, V value, long ttl) {
18: Entry e = new Entry(key, value, ttl);
19: e.addFirst();
20: return e;
21: }
22:
23: public Map<K, V> evict(Cache<K, V> c) {
24: Entry last = header.previous;
25: last.discard();
26: HashMap<K, V> m = new HashMap<K, V>(1);
27: m.put(last.getKey(), last.getValue());
28: return m;
29: }
30:
31: public synchronized void clear() {
32: synchronized (header) {
33: header.next = null;
34: header.previous = null;
35: }
36: }
37:
38: protected class Entry extends AbstractCacheEntry<K, V> {
39: protected Entry next;
40: protected Entry previous;
41:
42: public Entry(K key, V value, long ttl) {
43: super (key, value, ttl);
44: }
45:
46: private void addFirst() {
47: synchronized (header) {
48: next = header.next;
49: previous = header;
50: header.next = this ;
51: next.previous = this ;
52: }
53: }
54:
55: public void touch() {
56: discard();
57: addFirst();
58: }
59:
60: public void discard() {
61: synchronized (header) {
62: previous.next = next;
63: next.previous = previous;
64: }
65: }
66: }
67: }
|