1
2
3
4
5
6
7
8
9
10
11
12 package ca.spaz.util;
13
14 import java.util.*;
15
16 /***
17 * A caching map implementation that provides a maximum number of stored objects.
18 * @author Chris Rose
19 */
20 public class CacheMap implements Map {
21
22 private Map backingMap;
23 private Queue orderStack;
24 private int maxCacheSize;
25
26 public CacheMap(int size) {
27 this.backingMap = new HashMap();
28 this.orderStack = new LinkedList();
29 this.maxCacheSize = size;
30 }
31
32
33
34
35 public int size() {
36 return backingMap.size();
37 }
38
39
40
41
42 public boolean isEmpty() {
43 return backingMap.isEmpty();
44 }
45
46
47
48
49 public boolean containsKey(Object key) {
50 return backingMap.containsKey(key);
51 }
52
53
54
55
56 public boolean containsValue(Object value) {
57 return backingMap.containsValue(value);
58 }
59
60
61
62
63 public Object get(Object key) {
64 assert(orderStack.size() == backingMap.size());
65
66 return backingMap.get(key);
67 }
68
69
70
71
72 public Object put(Object arg0, Object arg1) {
73 assert(orderStack.size() == backingMap.size());
74 if (!orderStack.contains(arg0)) {
75 if (orderStack.size() >= maxCacheSize) {
76 prepQueue();
77 }
78 orderStack.offer(arg0);
79 backingMap.put(arg0, arg1);
80 } else {
81 assert(backingMap.containsKey(arg0));
82 }
83 assert(orderStack.size() == backingMap.size());
84 assert(backingMap.size() <= maxCacheSize);
85 return null;
86 }
87
88 private void prepQueue() {
89 while (orderStack.size() >= maxCacheSize) {
90 Object key = orderStack.remove();
91 Object res = backingMap.remove(key);
92 assert (res != null);
93 }
94 }
95
96
97
98
99 public Object remove(Object key) {
100 assert(orderStack.size() == backingMap.size());
101 orderStack.remove(key);
102 Object ret = backingMap.remove(key);
103 assert(orderStack.size() == backingMap.size());
104 return ret;
105 }
106
107
108
109
110 public void putAll(Map arg0) {
111 assert(orderStack.size() == backingMap.size());
112 for (Iterator iter = arg0.entrySet().iterator(); iter.hasNext();) {
113 Map.Entry entry = (Map.Entry) iter.next();
114 put(entry.getKey(), entry.getValue());
115 }
116 assert(orderStack.size() == backingMap.size());
117 }
118
119
120
121
122 public void clear() {
123 orderStack.clear();
124 backingMap.clear();
125 }
126
127
128
129
130 public Set keySet() {
131 return backingMap.keySet();
132 }
133
134
135
136
137 public Collection values() {
138 return backingMap.values();
139 }
140
141
142
143
144 public Set entrySet() {
145 return backingMap.entrySet();
146 }
147
148 public boolean equals(Object obj) {
149 return backingMap.equals(obj);
150 }
151
152 public int hashCode() {
153 return backingMap.hashCode();
154 }
155
156 public String toString() {
157 return backingMap.toString();
158 }
159
160 }