{"id":37697,"date":"2009-03-14T23:06:05","date_gmt":"2009-03-14T23:06:05","guid":{"rendered":"https:\/\/www.viafirma.com\/implementing-a-simple-object-cache-with-ehcache\/"},"modified":"2026-01-23T11:42:11","modified_gmt":"2026-01-23T11:42:11","slug":"implementing-a-simple-object-cache-with-ehcache","status":"publish","type":"post","link":"https:\/\/www.viafirma.com\/en\/implementing-a-simple-object-cache-with-ehcache\/","title":{"rendered":"Implementing a simple object cache with Ehcache"},"content":{"rendered":"\r\n<p class=\"wp-block-paragraph\"><em>Recently I have been reviewing the technical architecture of a Java EE project that was having serious scalability problems. In Development everything was going like a shot, but with a significant but not outrageous number of records (just 100,000) we were encountering response times for some of the online operations that could take up to 5 minutes. Obviously these times are not acceptable for a web operation, so it was urgent to detect sources of problems and optimize processes.<\/em><\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Actually, there was no part of the code that was 100% at fault, but the implemented functionality, excessively flexible for the user, allowed the user to perform searches and operations that finally implied a succession of queries, filtering, union\/intersection operations of huge lists, persistence&#8230;<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">For many of the lists that were handled, it was possible to guarantee their invariability over a long period of time. Data, for example, relating to provinces. Therefore, it seemed that implementing a cache of these lists, and especially of the final results after the aforementioned join\/intersection operations, etc., could be appropriate. It is true that Hibernate allows result caching (and in fact uses Ehcache), but in this case we are talking about post-processed results, so it would not be enough.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Caching objects in a Java EE application is basically trivial: we always have the option to place the object in application context (ServletContext) and retrieve it whenever we want. However, this approach is still something &#8220;toy&#8221;. We decided to use Ehcache in the first place because we knew that Hibernate took good advantage of it, but above all because, with an extremely simple development, we obtain important functional advantages such as:<\/p>\r\n\r\n\r\n\r\n<ul class=\"wp-block-list\">\r\n<li>Content expiration management. After a certain time, the cache deletes the cached object and starts returning NULL to subsequent requests. It removes the responsibility of persisting the lifetime of a cached object.<\/li>\r\n<li>Configuration of the maximum number of objects to cache in memory. You can set the number of objects to cache in memory. Ehcache takes care of serializing to disk everything that is left over, and retrieve it when necessary. It goes without saying that all objects to be cached must be serializable.<\/li>\r\n<li>Possibility of cluster deployment.<\/li>\r\n<li>Cache deletion during application server shutdown.<\/li>\r\n<li>Don&#8217;t reinvent the wheel!<\/li>\r\n<\/ul>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">In the end we developed a simple Manager class, implementing the Singleton pattern, which interacts with Ehcache. And in certain areas of the application, invoke the cache to retrieve the objects that were previously generated online.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">I&#8217;m going to put the code, because in the end, without a little help, this will come to nothing \ud83d\ude42 However, I would like to emphasize that the process of 5 minutes at the end, with a little love, has become responsive in less than 10 seconds. A gain of 3000%&#8230;<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code><code style=\"max-width: 100%; display: block;\">\r\n\/*\r\n\r\n* File: CacheUtil.java\r\n\r\n*\r\n\r\n* Created on march 2009\r\n\r\n*\r\n\r\n*\r\n\r\n* Copyright 2006-2029 Javier Echeverr\u00eda Us\u00faa (javieu at gmail.com)\r\n\r\n*\r\n\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n\r\n* you may not use this file except in compliance with the License.\r\n\r\n* You may obtain a copy of the License at\r\n\r\n*\r\n\r\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n*\r\n\r\n* Unless required by applicable law or agreed to in writing, software\r\n\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n\r\n* See the License for the specific language governing permissions and\r\n\r\n* limitations under the License.\r\n\r\n*\r\n\r\n*\/\r\n\r\npackage com.viavansi.framework.core.cache<\/code><\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>import net.sf.ehcache.Cache;<br \/>import net.sf.ehcache.CacheManager;<br \/>import net.sf.ehcache.Element;<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>import org.apache.commons.logging.Log;<br \/>import org.apache.commons.logging.LogFactory;<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>import com.viavansi.framework.core.persistencia.servicios.excepciones.ExcepcionServicio;<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>\/**<br \/>* @author Javier Echeverria Usua (javieu at gmail.com)<br \/>* @author Felix Garcia Borrego (borrego at gmail.com)<br \/>* @author Alexis Castilla Armero (pencerval at gmail.com)<br \/>*\/<br \/>public class CacheUtil {<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>public Object getCachedObject(String key) throws Exception{<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>if(minutosVidaDefault == 0)<br \/>minutosVidaDefault = MINUTOS_DEFAULT;<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>return getCachedObject(key, minutosVidaDefault);<br \/>}<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>public void putCachedObject(String key, Object info) throws Exception{<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>if(minutosVidaDefault == 0)<br \/>minutosVidaDefault = MINUTOS_DEFAULT;<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>putCachedObject(key, info, minutosVidaDefault);<br \/>}<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>public Object getCachedObject(String key, int minutosCache) throws Exception{<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>Cache cacheCustodia = getInstance(minutosCache);<br \/>Element element = cacheCustodia.get(key);<br \/>if(element != null){<br \/>return cacheCustodia.get(key).getValue();<br \/>}<br \/>else{<br \/>return null;<br \/>}<br \/>}<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>public void putCachedObject(String key, Object info, int minutosCache) throws Exception{<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>Cache cacheCustodia = getInstance(minutosCache);<br \/>cacheCustodia.put(new Element(key,info));<br \/>}<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>private Cache getInstance(int minutosCache) {<br \/>Cache cache = null;<br \/>\/\/Todav\u00eda no existe<br \/>int timeTolife = minutosCache * 60;<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>CacheManager manager = CacheManager.getInstance();<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>String nombreCache = \"viavansiCachedInfo\" + minutosCache;<\/code><\/pre>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>if (manager.cacheExists(nombreCache)) {<br \/>cache = manager.getCache(nombreCache);<br \/>} else {<br \/>\/\/ Configuramos el apagado en caso de Error de la JVM o parada inesperada.<br \/>System.setProperty(\"net.sf.ehcache.enableShutdownHook\", \"true\");<br \/>manager.addCache(new Cache(nombreCache, 100, true, false, timeTolife, timeTolife));<br \/>cache = manager.getCache(nombreCache);<br \/>}<\/code><\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">return cache;<br \/>}<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">public static void shutDown() {<br \/>CacheManager.getInstance().shutdown();<br \/>}<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">private int MINUTOS_DEFAULT = 60;<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">private static int minutosVidaDefault = 0;<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">protected CacheUtil(int minutosVida) {<br \/>minutosVidaDefault = minutosVida;<br \/>}<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">public static void init(int minutosVida) {<br \/>minutosVidaDefault = minutosVida;<br \/>}<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">\/* * Constructor y accesores *\/<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">\/\/ Singleton Pattern private static CacheUtil singleton;<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">\/\/Commons Logging Instance private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">\/** * private constructor (just an instance). * @return AmbitoBO *\/ protected CacheUtil() throws ExcepcionServicio { super(); log.debug(&#8220;Creating a new instance of CacheUtil&#8221;); }<\/p>\r\n<p>&nbsp;<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code><code>\/**<br \/>\r\n* Devuelve instancia activa de AmbitoBO.<br \/>\r\n* T\u00edpico m\u00e9todo de implementaci\u00f3n de patr\u00f3n singleton<br \/>\r\n* @return AmbitoBO<br \/>\r\n* @throws ExcepcionServicio<br \/>\r\n*\/<br \/>\r\npublic static CacheUtil getCurrentInstance() throws ExcepcionServicio {<br \/>\r\nif (singleton == null) {<br \/>\r\ntry {<br \/>\r\nsingleton = new CacheUtil();<br \/>\r\n} catch (ExcepcionServicio e) {<br \/>\r\nthrow e;<br \/>\r\n}<br \/>\r\n}<br \/>\r\nreturn singleton;<br \/>\r\n}<br \/>\r\n}<br \/>\r\n<\/code><br \/>Un saludo a todos, y poned una cach\u00e9 en vuestros corazones :-P<br \/><br \/><br \/><br \/><br \/><\/code><\/pre>\r\n\r\n<p><span style=\"font-weight: 400;\"><div class=\"vf_related_posts_wrapper\"><h2 class=\"vf_related_posts_title\">Informaci\u00f3n relacionada<\/h2><div class=\"vf_related_posts\"><article class=\"vc_gitem-post-data-source-post\"><a href=\"https:\/\/www.viafirma.com\/en\/basic-tips-cybersecurity-company\/\"><div class=\"vc_gitem-post-image\"><img loading=\"lazy\" decoding=\"async\" width=\"768\" height=\"475\" src=\"https:\/\/www.viafirma.com\/wp-content\/uploads\/2018\/08\/blog_consejos_ciber-768x475.webp\" class=\"attachment-medium_large size-medium_large wp-post-image\" alt=\"imagen de ordenador con candados ciberseguridad\" srcset=\"https:\/\/www.viafirma.com\/wp-content\/uploads\/2018\/08\/blog_consejos_ciber-768x475.webp 768w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2018\/08\/blog_consejos_ciber-300x186.webp 300w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2018\/08\/blog_consejos_ciber-1024x634.webp 1024w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2018\/08\/blog_consejos_ciber.webp 1228w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/div><\/a><div class=\"vc_gitem-post-data\"><h3 class=\"vc_gitem-post-data-source-post_title\"><a href=\"https:\/\/www.viafirma.com\/en\/basic-tips-cybersecurity-company\/\">5 basic tips to improve cybersecurity in your company<\/a><\/h3><p>Cybersecurity is, today, one of the main aspects that companies<\/p><\/div><\/article><article class=\"vc_gitem-post-data-source-post\"><a href=\"https:\/\/www.viafirma.com\/en\/artificial-intelligence-machine-learning\/\"><div class=\"vc_gitem-post-image\"><img loading=\"lazy\" decoding=\"async\" width=\"768\" height=\"475\" src=\"https:\/\/www.viafirma.com\/wp-content\/uploads\/2017\/08\/blog_robots-768x475.webp\" class=\"attachment-medium_large size-medium_large wp-post-image\" alt=\"Robot inteligencia artificial\" srcset=\"https:\/\/www.viafirma.com\/wp-content\/uploads\/2017\/08\/blog_robots-768x475.webp 768w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2017\/08\/blog_robots-300x186.webp 300w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2017\/08\/blog_robots-1024x634.webp 1024w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2017\/08\/blog_robots.webp 1228w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/div><\/a><div class=\"vc_gitem-post-data\"><h3 class=\"vc_gitem-post-data-source-post_title\"><a href=\"https:\/\/www.viafirma.com\/en\/artificial-intelligence-machine-learning\/\">How do the machines learn?<\/a><\/h3><p>For some time, we have seen how one of the<\/p><\/div><\/article><article class=\"vc_gitem-post-data-source-post\"><a href=\"https:\/\/www.viafirma.com\/en\/e-signature-myths\/\"><div class=\"vc_gitem-post-image\"><img loading=\"lazy\" decoding=\"async\" width=\"768\" height=\"475\" src=\"https:\/\/www.viafirma.com\/wp-content\/uploads\/2025\/07\/010725_blog_firmaelectronica-768x475.webp\" class=\"attachment-medium_large size-medium_large wp-post-image\" alt=\"Person signing a document on a tablet, illustrationg e-signature myths and their validation\" srcset=\"https:\/\/www.viafirma.com\/wp-content\/uploads\/2025\/07\/010725_blog_firmaelectronica-768x475.webp 768w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2025\/07\/010725_blog_firmaelectronica-300x186.webp 300w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2025\/07\/010725_blog_firmaelectronica-1024x634.webp 1024w, https:\/\/www.viafirma.com\/wp-content\/uploads\/2025\/07\/010725_blog_firmaelectronica.webp 1228w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/div><\/a><div class=\"vc_gitem-post-data\"><h3 class=\"vc_gitem-post-data-source-post_title\"><a href=\"https:\/\/www.viafirma.com\/en\/e-signature-myths\/\">E-signature myths<\/a><\/h3><p>Debunking 5 myths about electronic signatures<\/p><\/div><\/article><\/div><\/div><\/span><\/p>","protected":false},"excerpt":{"rendered":"Recently I have been reviewing the technical architecture of a...","protected":false},"author":1,"featured_media":35659,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"default","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[157],"class_list":["post-37697","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-others"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/posts\/37697","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/comments?post=37697"}],"version-history":[{"count":3,"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/posts\/37697\/revisions"}],"predecessor-version":[{"id":97656,"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/posts\/37697\/revisions\/97656"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/media\/35659"}],"wp:attachment":[{"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/media?parent=37697"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.viafirma.com\/en\/wp-json\/wp\/v2\/categories?post=37697"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}