01: package com.completex.objective.components.ocache.impl;
02:
03: import com.completex.objective.components.ocache.OdalCacheConfig;
04: import com.completex.objective.components.ocache.ConfigurableCache;
05:
06: import java.util.Map;
07: import java.util.List;
08: import java.util.HashMap;
09: import java.util.LinkedList;
10:
11: /**
12: * @author Gennady Krizhevsky
13: */
14: public class ExpiringLruCache extends AbstractExpiringCache implements
15: ConfigurableCache {
16:
17: private String name;
18: private int maxSize = 100;
19: private Map map;
20: private List keys;
21:
22: public void configure(OdalCacheConfig cacheConfig) {
23: maxSize = cacheConfig.getMaxSize();
24: setCacheFlushInterval(cacheConfig.getCacheFlushInterval());
25: setEntryFlushInterval(cacheConfig.getEntryFlushInterval());
26: }
27:
28: public void configure(Map cacheConfigMap) {
29: OdalCacheConfig cacheConfig = new OdalCacheConfig(
30: cacheConfigMap);
31: configure(cacheConfig);
32: }
33:
34: public ExpiringLruCache(String name) {
35: this .name = name;
36: this .map = new HashMap();
37: this .keys = new LinkedList();
38: }
39:
40: public ExpiringLruCache() {
41: this (null);
42: }
43:
44: protected ExpiringValue doGet(Object key) {
45: Object value = map.get(key);
46: keys.remove(key);
47: if (value != null) {
48: keys.add(key);
49: }
50: return (ExpiringValue) value;
51: }
52:
53: protected Object doPut(Object key, Object value) {
54: Object oldValue = null;
55: map.put(key, value);
56: keys.add(key);
57: if (keys.size() > maxSize && keys.size() > 0) {
58: Object firstKey = keys.remove(0);
59: oldValue = map.remove(firstKey);
60: }
61: return oldValue;
62: }
63:
64: public synchronized Object remove(Object key) {
65: keys.remove(key);
66: return map.remove(key);
67: }
68:
69: public synchronized void clear() {
70: map.clear();
71: keys.clear();
72: }
73:
74: public String getName() {
75: return name;
76: }
77:
78: public void setName(String name) {
79: this .name = name;
80: }
81:
82: public int getMaxSize() {
83: return maxSize;
84: }
85:
86: }
|