1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.ibatis.sqlmap.engine.cache.lru;
17
18 import com.ibatis.sqlmap.engine.cache.CacheController;
19 import com.ibatis.sqlmap.engine.cache.CacheModel;
20
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Properties;
27
28
29
30
31 public class LruCacheController implements CacheController {
32
33
34 private int cacheSize;
35
36
37 private Map cache;
38
39
40 private List keyList;
41
42
43
44
45 public LruCacheController() {
46 this.cacheSize = 100;
47 this.cache = Collections.synchronizedMap(new HashMap());
48 this.keyList = Collections.synchronizedList(new LinkedList());
49 }
50
51
52
53
54
55
56 public int getCacheSize() {
57 return cacheSize;
58 }
59
60
61
62
63
64
65
66 public void setCacheSize(int cacheSize) {
67 this.cacheSize = cacheSize;
68 }
69
70
71
72
73
74
75
76 public void setProperties(Properties props) {
77 String size = props.getProperty("cache-size");
78 if (size == null) {
79 size = props.getProperty("size");
80 }
81 if (size != null) {
82 cacheSize = Integer.parseInt(size);
83 }
84 }
85
86
87
88
89
90
91
92
93
94
95
96 public void putObject(CacheModel cacheModel, Object key, Object value) {
97 cache.put(key, value);
98 keyList.add(key);
99 if (keyList.size() > cacheSize) {
100 try {
101 Object oldestKey = keyList.remove(0);
102 cache.remove(oldestKey);
103 } catch (IndexOutOfBoundsException e) {
104
105 }
106 }
107 }
108
109
110
111
112
113
114
115
116
117
118
119 public Object getObject(CacheModel cacheModel, Object key) {
120 Object result = cache.get(key);
121 keyList.remove(key);
122 if (result != null) {
123 keyList.add(key);
124 }
125 return result;
126 }
127
128 public Object removeObject(CacheModel cacheModel, Object key) {
129 keyList.remove(key);
130 return cache.remove(key);
131 }
132
133
134
135
136
137
138
139 public void flush(CacheModel cacheModel) {
140 cache.clear();
141 keyList.clear();
142 }
143
144 }