1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package com.macvu.tiles.cache;
20
21 import java.util.Map;
22 import java.util.Collections;
23 import java.io.Serializable;
24
25 import org.apache.commons.collections.map.LRUMap;
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28
29 /***
30 * User: MVu
31 */
32 public class LRUCacheService implements CacheService {
33 protected Log logger = LogFactory.getLog(this.getClass());
34
35 private static final int DEFAULT_MAX_CACHE_SIZE = 40000;
36
37 int maxCacheSize = DEFAULT_MAX_CACHE_SIZE;
38
39
40
41 /***
42 * caching HTML
43 */
44 Map cacheMap;
45
46 public LRUCacheService() {
47 initiateCacheMap();
48 }
49
50 public LRUCacheService(int maxCacheSize) {
51 this.maxCacheSize = maxCacheSize;
52 initiateCacheMap();
53 }
54
55 protected void initiateCacheMap() {
56 Map regularMap = new LRUMap(maxCacheSize);
57 cacheMap = Collections.synchronizedMap(regularMap);
58 }
59
60 public void invalidateCache() {
61 initiateCacheMap();
62 }
63
64 public int getMaxCacheSize() {
65 return maxCacheSize;
66 }
67
68 /***
69 * Set the maximum cache size. If max size is reach, the least recent used item is remove before another item can be
70 * placed on the cache. NOTE: cache is clear when the size is change.
71 *
72 * @param maxCacheSize size of the cache.
73 */
74 public void setMaxCacheSize(int maxCacheSize) {
75 if (this.maxCacheSize != maxCacheSize) {
76 this.maxCacheSize = maxCacheSize;
77 initiateCacheMap();
78 }
79 }
80
81 /***
82 * add result to cache map
83 *
84 * @param key
85 * @param result
86 */
87 public boolean store(Serializable key, Serializable result) {
88 cacheMap.put(key, result);
89
90 return true;
91 }
92
93 /***
94 * get result from cache map
95 *
96 * @param key
97 * @return
98 */
99 public Serializable retrieve(Serializable key) {
100 Serializable result = (Serializable) cacheMap.get(key);
101
102 if (logger.isDebugEnabled()) {
103 if (result != null) {
104 logger.debug("Result Key " + key + " found in cache.");
105 } else {
106 logger.debug("Result Key " + key + " NOT found in cache.");
107 }
108 }
109
110 return result;
111 }
112
113 }
114