• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Ehcache Example

September 16, 2015 //  by Krishna Srinivasan//  Leave a Comment

Ehcache is most widely used Java open source cache implementation. The great advantage of this cache is that it easily integrates with any other libraries. In this tutorial I will write very basic example using the Ehcache library.

The latest version:

  • The latest version of ehcache is 2.10.1. You can download the latest distributations of ehcache is from here.
  • There is a milestone release

Also Read : Spring Cache Tutorial

Here is the project structure for this example. It is very simple example that stores the data in the disk using the ehcache.xml configurations.

  1. Project Structure
  2. Maven dependencies
  3. Cache implementation class
  4. ehcache.xml configurations
  5. Output

ehcache

pom.xml

<dependencies>
      <dependency>
		<groupId>net.sf.ehcache</groupId>
		<artifactId>ehcache</artifactId>
		<version>2.10.1</version>
	</dependency>
  </dependencies>

EhcacheExample.java

public class EhcacheExample {

	public static void main(String[] args) {

		//Create a cache manager
		CacheManager cm = CacheManager.getInstance();

		//Create a cache called "cacheStore"
		//cm.addCache("cacheStore");

		//Get a cache called "cacheStore"
		Cache cache = cm.getCache("cacheStore");

		//Add few elements in to cache
		UserDetails details = new UserDetails("001","First Name","Last Name");
		cache.put(new Element("1", details));
		cache.put(new Element("2", "Two"));
		cache.put(new Element("3", "Three"));

		//Get the element from cache
		Element ele = cache.get("1");
		UserDetails u = (UserDetails)ele.getObjectValue();
		System.out.println(u.getUserId());

		//Whether key is in the cache?
		System.out.println(cache.isKeyInCache("1"));
		System.out.println(cache.isKeyInCache("5"));

		//Call shutdown to close the cache manager
		cm.shutdown();

	}

}

ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true">

	<!-- By default, Ehcache stored the cached files in temp folder. -->
	<!-- <diskStore path="java.io.tmpdir" /> -->
	
	<!-- Ask Ehcache to store cache in this path -->
	<diskStore path="d:\\cache" />

	<!-- Sample cache named cacheStore This cache contains a maximum in memory of 10000 elements, and will expire an element if it is idle for more than 5 minutes and lives for more than 10 minutes. If there are more than 10000 elements it will overflow to the disk cache, which in this configuration will go to wherever java.io.tmp is defined on your system. On a standard Linux system this will be /tmp" -->
	<cache name="cacheStore" maxEntriesLocalHeap="10000" maxEntriesLocalDisk="1000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off">
		<persistence strategy="localTempSwap" />
	</cache>

</ehcache>

UserDetails.java

public class UserDetails {
	private String userId;
	private String firstName;
	private String lastName;
	public UserDetails(){}
	public UserDetails(String userId,String firstName,String lastName){
		this.userId = userId;
		this.firstName = firstName;
		this.lastName = lastName;
	}
	// setters and getters here		
}

Output:

Here is the output for the ehcache example program.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
001
true
false

EHcache.xml Attributes

If you are working with Ehcache configuration, then it is very important to understand the meaning and usage of each and every element and attribute used in the ehcache.xml file. Here I am explaining the use of some of the useful attributes that are most commonly used in the ehcache configurations.

defaultCache

This element is a mandatory default cache configuration. These settings will be applied to caches created programmtically using CacheManager.add(String cacheName). The defaultCache has an implicit name “default” which is a reserved cache name.

maxElementsInMemory

The attribute tells the Ehcache that how many caches would be stored in the memory. If the total caches reached the limit, then the caches will be pushed to the disk if the configurations set as overflowToDisk=true. If this attribute set as false, old caches will be evicted and new caches will be replace the old one.

eternal

If this attribute is set as true, then other attributes timeToIdleSecondsand timeToLiveSeconds need not be configured. If you configure these attributes, then the configure values will not be considered. The default value of 0 will be taken for both the attributes. Note that, the configuration eternal=true implies that caching configuration should not consider the timeToIdleSeconds and timeToLiveSeconds. It means that the caches will not be expired for ever in the store. It has to be cleared manually by the server administrator by restarting the server. Be careful on using this attribute.

overflowToDisk

This attribute sets whether cache elements can overflow to disk when the memory store has reached the maxElementsInMemory limit. If the attribute set to false, cache elements will not overflow to disk when store has reached the maxElementsInMemory limit.

timeToIdleSeconds

This attribute sets the idle time before it expires. For example, if you set this attribute as 10, the caches that are not accessed for 10 seconds will be automatically expired. The default value for this attribute is 0. If the value is 0, this attribute will not be considered for the expiration. timeToIdleSeconds is valid only when eternal attribute value is false.

timeToLiveSeconds

This attribute sets the total expiry time for the cache. It is the time between creating time and expiration time. The default value for this attribute is 0. If the value is 0, this attribute will not be considered for the expiration. timeToLiveSeconds is valid only when eternal attribute value is false.

maxElementsOnDisk

This attribute sets the maximum number of objects that will be maintained in the DiskStore. The default value is zero, meaning unlimited. This attribute has been deprecated from the version 2.5.

maxEntriesLocalDisk vs maxElementsOnDisk

maxElementsOnDisk is the historical name, deprecated since 2.5 This attribute is replaced by new attribute maxElementsLocalDisk. But the new attribute controls the exact same internal variable.

Where the cache files are stored?

The default disk store path for the cache file is the default temp directory of the operating system. For example, if you are running it on linux, the default path would be /tmp. Please cont’ confuse with the temp directory of the application server. Here is the pre-defined variables to specifying the default directories.

  • user.home – User’s home directory
  • user.dir – User’s current working directory
  • java.io.tmpdir – Default temp file path
  • ehcache.disk.store.dir – A system property

If you want to create a sub-directory, it can be specified as e.g. java.io.tmpdir/one

Exceptions

If you are getting the following exception, then the most likely reason is that you are missing the spring-context-support.jar file. This file actually contains the org.springframework.cache.ehcache.EhCacheCacheManager file.

Caused by: java.lang.ClassNotFoundException: org.springframework.cache.ehcache.EhCacheCacheManager
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1718)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
	at org.springframework.util.ClassUtils.forName(ClassUtils.java:266)
	at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:419)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1302)
	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1273)
	... 31 more

You can resolve the above exception by adding the following dependency in your pom.xml file:

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>X.Y.Z.RELEASE</version>
</dependency>

Category: JavaTag: Ehcache Tutorials

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « ExpressJS Session Store using MongoDB, PostgreSQL
Next Post: Spring Security Tutorial using Spring Boot »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact