View Javadoc

1   /**
2    * This file Copyright (c) 2008-2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
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   * Magnolia cache wrapper for underlying ehCache implementation.
48   * @author gjoseph
49   * @version $Revision: $ ($Author: $)
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          // we can't use isKeyInCache(), as it does not check for the element's expiration
85          // which may lead to unexpected results.
86          // return ehcache.isKeyInCache(key);
87          try {
88              // get() and getQuiet() do check for expiration and return null if the element was expired.
89              // we can't use getQuiet, as it's non-blocking which could lead to multiple copies of same page to be generated
90              // if page is requested while previous request for same page is still being processed by different thread
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              // FYI: in case you want to return some value instead of re-throwing exception: this is a dilemma ... obviously resource does not exist yet, but being stuck here for while means that it is either being generated or it takes time to generate.
95              // returning false would mean server attempts to generate the response again, possibly loosing another thread in the process
96              // returning true means server will assume resource exists and will try to retrieve it later, possibly failing with the same error
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 }