Getting Started with Ehcache

Ehcache is a widely used caching system in Java world. Have been seeing requests for a simple getting started tutorial for the Ehcache. Ehcache is fairly simple to use.

Pre-requisites

Java 6+

If it's a maven project, add the following entry in your pom.xml

<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
  <version>2.9.0</version>
</dependency>

If it's simple Java project in IDE, add ehcache jar to your classpath.

In Ehcache, CacheManager is the central Entity. A single CacheManager manages multiple caches and is responsible for it managing the life-cycle of Caches. Each Cache is uniquely identified by a Name provided by the user.

Let's look at a very simple usage. You can get the complete code at EhcacheDemo.java

public static void simpleCacheDemo() {
    CacheManager cacheManager = CacheManager.newInstance();
    Ehcache cache = cacheManager.addCacheIfAbsent("testCache");

    Element cacheElement1 = new Element("Key-1", "Value-1");
    Element cacheElement2 = new Element("Key-2", "Value-2");
    Element cacheElement3 = new Element("Key-3", "Value-3");
    cache.put(cacheElement1);
    cache.put(cacheElement2);
    cache.put(cacheElement3);

    System.out.println(cache.get("Key-1").getObjectValue());
    System.out.println(cache.get("Key-3").getObjectValue());
    System.out.println(cache.isKeyInCache("Key-4"));
    System.out.println(cache.isKeyInCache("Key-1"));

    cacheManager.shutdown();
  }

Here are the simple steps

  • Create an instance of CacheManager. Here we use the simply use createInstance() API for simplicity. You can pass parameters as well
  • Since we have not provided any configuration, our CacheManager won't have the testCache. So let's create Cache using addCacheIfAbsent(). You can use addCache() as well. This would add a Cache with name testCache
  • To add entry to Cache, we have to use Element class. We create instance of Element class, passing Key and Value to the constructor and call put on the Cache. The Element is now added to the Cache
  • We can get the value for a particular key by calling get() API. get() API would return null, if an element is not present, so be sure to check for null. You can get the value by calling getObjectValue() API on the Element instance
  • You can also also query the Cache for keys using isKeyInCache() API
  • Shutdown the CacheManager once done, else the program won't exit

Example output

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.
Value-1
Value-3
false
true

Ignore the slf4j warning. If you provide a logger implementation this would go.

In the example above, we have used default settings. We can programatically configure the CacheManager and Caches as well. Lets look at the same example with programatic configuration.

 public static void ehcacheProgramaticConfiguration() {
    CacheConfiguration cacheConfiguration = new CacheConfiguration();
    cacheConfiguration.setName("testCache");
    cacheConfiguration.setMaxEntriesLocalHeap(1000);
    cacheConfiguration.setTimeToLiveSeconds(1000);

    Configuration cacheManagerConfiguration = new Configuration();
    cacheManagerConfiguration.addCache(cacheConfiguration);
    CacheManager cacheManager = CacheManager.create(cacheManagerConfiguration);

    Ehcache cache = cacheManager.getEhcache("testCache");
    // refer example above for cache operations
}

In the code snippet above, we see the programatic configuration of CacheManager and Cache. We can create many Cache configurations and then add to Configuration object which contains the CacheManager configuration. In the snippet above, since we have added out testCache, we simple call getCache() API on CacheManager.

Explore more configuration options at Ehcache site

Leave a 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.