39 |
private HashMap map = new HashMap(); |
private HashMap map = new HashMap(); |
40 |
private int maxEntries; |
private int maxEntries; |
41 |
|
|
42 |
|
/** An interface for values that need to know when they |
43 |
|
* are removed from the map. |
44 |
|
*/ |
45 |
|
public interface Removable { |
46 |
|
/** Called when this value was removed (from the given key. |
47 |
|
*/ |
48 |
|
void wasRemoved(Object key); |
49 |
|
} |
50 |
|
|
51 |
|
/** Create a new cachingmap with the given maximum number of entries. |
52 |
|
* @param maxEntries Number of entries to keep. 0 = don't cache anything. |
53 |
|
*/ |
54 |
public CachingMap(int maxEntries) { |
public CachingMap(int maxEntries) { |
55 |
this.maxEntries = maxEntries; |
this.maxEntries = maxEntries; |
56 |
if(maxEntries < 0) throw new Error("Can't keep so few."); |
if(maxEntries < 0) throw new Error("Can't keep so few."); |
63 |
int toRemove = map.size() - maxEntries; |
int toRemove = map.size() - maxEntries; |
64 |
while(toRemove-- > 0) { |
while(toRemove-- > 0) { |
65 |
Iterator i = map.keySet().iterator(); |
Iterator i = map.keySet().iterator(); |
66 |
for(int nth = (int)(Math.random() * 22); nth > 0; nth--) { |
for(int nth = (int)(Math.random() * map.size()); nth > 0; nth--) { |
67 |
i.next(); |
i.next(); |
68 |
if(!i.hasNext()) |
if(!i.hasNext()) |
69 |
i = map.keySet().iterator(); |
i = map.keySet().iterator(); |
70 |
} |
} |
71 |
i.next(); |
Object rkey = i.next(); |
72 |
i.remove(); |
Object rval = map.get(key); |
73 |
|
if(rval instanceof Removable) |
74 |
|
((Removable)rval).wasRemoved(rkey); |
75 |
|
map.remove(rkey); |
76 |
} |
} |
77 |
return ret; |
return ret; |
78 |
} |
} |