1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.cache.decorators;
17
18 import java.util.LinkedHashMap;
19 import java.util.Map;
20
21 import org.apache.ibatis.cache.Cache;
22
23
24
25
26
27
28 public class LruCache implements Cache {
29
30 private final Cache delegate;
31 private Map<Object, Object> keyMap;
32 private Object eldestKey;
33
34 public LruCache(Cache delegate) {
35 this.delegate = delegate;
36 setSize(1024);
37 }
38
39 @Override
40 public String getId() {
41 return delegate.getId();
42 }
43
44 @Override
45 public int getSize() {
46 return delegate.getSize();
47 }
48
49 public void setSize(final int size) {
50 keyMap = new LinkedHashMap<Object, Object>(size, .75F, true) {
51 private static final long serialVersionUID = 4267176411845948333L;
52
53 @Override
54 protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {
55 boolean tooBig = size() > size;
56 if (tooBig) {
57 eldestKey = eldest.getKey();
58 }
59 return tooBig;
60 }
61 };
62 }
63
64 @Override
65 public void putObject(Object key, Object value) {
66 delegate.putObject(key, value);
67 cycleKeyList(key);
68 }
69
70 @Override
71 public Object getObject(Object key) {
72 keyMap.get(key);
73 return delegate.getObject(key);
74 }
75
76 @Override
77 public Object removeObject(Object key) {
78 return delegate.removeObject(key);
79 }
80
81 @Override
82 public void clear() {
83 delegate.clear();
84 keyMap.clear();
85 }
86
87 private void cycleKeyList(Object key) {
88 keyMap.put(key, key);
89 if (eldestKey != null) {
90 delegate.removeObject(eldestKey);
91 eldestKey = null;
92 }
93 }
94
95 }