1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.module.cache.ehcache;
35
36
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import info.magnolia.module.cache.mbean.CacheMonitor;
41 import net.sf.ehcache.Ehcache;
42 import net.sf.ehcache.Element;
43 import net.sf.ehcache.constructs.blocking.BlockingCache;
44 import net.sf.ehcache.constructs.blocking.LockTimeoutException;
45
46
47
48
49
50
51 public class EhCacheWrapper implements info.magnolia.module.cache.BlockingCache {
52
53 private static final Logger log = LoggerFactory.getLogger(EhCacheWrapper.class);
54 private final BlockingCache ehcache;
55 private String name;
56
57 public EhCacheWrapper(BlockingCache ehcache, String name) {
58 this.ehcache = ehcache;
59 this.name = name;
60 }
61
62 public EhCacheWrapper(Ehcache ehcache, String name) {
63 this(castToBlockingCacheOrThrowException(ehcache), name);
64 }
65
66 private static BlockingCache castToBlockingCacheOrThrowException(Ehcache ehcache) {
67 if(!(ehcache instanceof BlockingCache)){
68 throw new RuntimeException("The current caching framework depends on the fact the a blocking cache is used.");
69 }
70 return (BlockingCache) ehcache;
71 }
72
73 public Object get(Object key) {
74 final Element element = ehcache.get(key);
75 try {
76 return element != null ? element.getObjectValue() : null;
77 } catch (LockTimeoutException e) {
78 log.error("Detected 1 thread stuck in generating response for {}. This might be temporary if obtaining the response is resource intensive or when accessing remote resources.", key);
79 throw e;
80 }
81 }
82
83 public boolean hasElement(Object key) {
84
85
86
87 try {
88
89
90
91 return ehcache.get(key) != null;
92 } catch (LockTimeoutException e) {
93 log.error("Detected 1 thread stuck in generating response for {}. This might be temporary if obtaining the response is resource intensive or when accessing remote resources.", key);
94
95
96
97 throw e;
98 }
99 }
100
101 public void put(Object key, Object value) {
102 final Element element = new Element(key, value);
103 ehcache.put(element);
104 }
105
106 public void put(Object key, Object value, int timeToLiveInSeconds) {
107 final Element element = new Element(key, value);
108 element.setTimeToLive(timeToLiveInSeconds);
109 ehcache.put(element);
110 }
111
112 public void remove(Object key) {
113 ehcache.remove(key);
114 }
115
116 public void clear() {
117 CacheMonitor.getInstance().countFlush(this.name);
118 ehcache.removeAll();
119 }
120
121 public void unlock(Object key) {
122 if(ehcache.getQuiet(key) == null) {
123 put(key, null);
124 remove(key);
125 }
126 }
127
128 public int getBlockingTimeout() {
129 return ehcache.getTimeoutMillis();
130 }
131
132 public Ehcache getWrappedEhcache() {
133 return ehcache;
134 }
135
136 public String getName() {
137 return name;
138 }
139
140 public int getSize() {
141 return ehcache.getSize();
142 }
143
144
145
146 }