1
2
3
4 package org.rcfaces.core.internal.lang;
5
6 import java.util.HashMap;
7 import java.util.LinkedList;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.WeakHashMap;
11
12 import org.apache.commons.logging.Log;
13 import org.apache.commons.logging.LogFactory;
14 import org.rcfaces.core.internal.Constants;
15
16
17
18
19
20
21 public class LimitedMap {
22 private static final String REVISION = "$Revision: 1.1 $";
23
24 private static final Log LOG = LogFactory.getLog(LimitedMap.class);
25
26
27
28 private final Map caches;
29
30 private final Map weakCache;
31
32 private final int maxCacheSize;
33
34 private List cacheList = new LinkedList();
35
36 public LimitedMap(int maxCacheSize) {
37 this.maxCacheSize = maxCacheSize;
38
39 caches = new HashMap(maxCacheSize + 2);
40
41 LOG.debug("Set max cache size to " + maxCacheSize + ".");
42
43 if (Constants.BASIC_CONTENT_WEAK_CACHE_ENABLED) {
44 weakCache = new WeakHashMap(maxCacheSize);
45 LOG.debug("Create a weak map initialized with size " + maxCacheSize
46 + ".");
47
48 } else {
49 weakCache = null;
50 }
51
52 }
53
54 public synchronized Object get(Object key) {
55 Cache cache = (Cache) caches.get(key);
56 if (cache == null && weakCache != null) {
57 cache = (Cache) weakCache.get(key);
58 }
59
60 if (cache == null) {
61 return null;
62 }
63
64 if (cacheList.get(0) != cache) {
65 cacheList.remove(cache);
66 cacheList.add(0, cache);
67 }
68
69 return cache.serializable;
70 }
71
72 public synchronized void remove(Object key) {
73 Cache cache = (Cache) caches.remove(key);
74 if (cache == null) {
75 return;
76 }
77 cacheList.remove(cache);
78 }
79
80 public synchronized void put(Object key, Object serializable) {
81 Cache cache = (Cache) caches.get(key);
82 if (cache != null) {
83 cache.serializable = serializable;
84
85 cacheList.remove(cache);
86
87 } else {
88 cache = new Cache(key, serializable);
89 caches.put(key, cache);
90 }
91
92 cacheList.add(0, cache);
93
94 int cacheSize = caches.size();
95
96 if (LOG.isDebugEnabled()) {
97 LOG
98 .debug("Register key='" + key + "' cacheSize=" + cacheSize
99 + ".");
100 }
101
102 if (cacheSize > maxCacheSize) {
103 Cache oldest = (Cache) cacheList.remove(cacheSize - 1);
104
105 caches.remove(oldest.key);
106
107 if (weakCache != null) {
108 weakCache.put(oldest.key, oldest);
109 }
110
111 if (LOG.isDebugEnabled()) {
112 LOG.debug("Remove the oldest cached.");
113 }
114 }
115 }
116
117 private String computeKey(String cmd, String url) {
118 return cmd + "\uffff" + url;
119 }
120
121
122
123
124
125
126 private static class Cache {
127 private static final String REVISION = "$Revision: 1.1 $";
128
129 final Object key;
130
131 Object serializable;
132
133 public Cache(Object key, Object serializable) {
134 this.key = key;
135 this.serializable = serializable;
136 }
137 }
138 }