Monday, 9 June 2014

Java Ehcache Simple Example

Ehca  che is an open source framework for caching objects. It is very simple and most widely used.
Here we will see one simple example to put one Student object in to cache and using that object from cache.
See more about Ehcache
1. Add below maven dependency
2. Create a Pojo class
public class Student implements Serializable {

private static final long serialVersionUID = -8642556460186434431L;
private Integer studId;
private String firstName;
private String lastname;

public Student(
Integer emplId, String firstName, String lastname) {
this.studId = emplId;
this.firstName = firstName;
this.lastname = lastname;
// Getters and setters
3. Create ehcache.xml configuration
This file needs to be placed in your resources folder (src/main/resources)
<ehcache name="StudentCache">
<defaultcache diskexpirythreadintervalseconds="120" diskpersistent="false"
diskspoolbuffersizemb="30" eternal="false" maxelementsinmemory="10000"
maxelementsondisk="10000000" memorystoreevictionpolicy="LRU" overflowtodisk="true"
timetoidleseconds="120" timetoliveseconds="120">
<cache eternal="false" maxelementsinmemory="100" maxelementsondisk="0"
memorystoreevictionpolicy="LFU" name="students" timetoidleseconds="120"
3. Create a class to load cache configuration
package com.vinod.ehcache;


import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

public class StudentEHCache {

private static final CacheManager cacheManager;
private Ehcache studentCache;

// Loading ehcache config file and creating CacheManager.
static {

ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
InputStream resourceAsStream = contextClassLoader.getResourceAsStream("ehcache.xml");
cacheManager = CacheManager.create(resourceAsStream);

public StudentEHCache() {
studentCache = cacheManager.getEhcache("students");

    * Creating new Element to hold student object
    *@param id
    *@param student
public void addStudent(Integer id, Student student) {
Element element = new Element(id, student);

    * Method to get Student object using id.
    *@param id
public Student getStudent(Integer id) {
Element element = studentCache.get(id);
if (element != null) {
return (Student) element.getValue();
return null;
4. Create a main class to test cache

package com.vinod.ehcache;

public class StudentCacheTest {
private StudentEHCache simpleEHCacheExample;

public StudentCacheTest() {
simpleEHCacheExample = new StudentEHCache();
simpleEHCacheExample.addStudent(1, new Student(1, "Vinod", "Bangalore"));



public static void main(String[] args) {
new StudentCacheTest();

5. Output  
Student [studId=1, firstName=Vinod, lastname=Bangalore]