The Recipes and Code Samples page contains recipes - short concise examples for specific use cases - and a set of code samples that will help you get started with Ehcache.
If you have a suggestion or an idea for a recipe or more code samples, please tell us about it using the mailing list or forums.
| Recipe | Description |
| Web Page and Fragment Caching | How to use inluded Servlet Filters to Cache Web Page and Web Page Fragments |
| Configure a Grails App for Clustering | How to configure a Grails Application for clustered Hibernate 2nd Level Cache |
| Data Freshness and Expiration | How to maintain cache "freshness" by configuring TTL and data expiration properly |
| Enable Terracotta Programmatically | How to enable Terracotta support for Ehcache programmatically |
| WAN Replication | 3 Strategies for configuring WAN replication |
| Caching Empty Values | Why caching empty values can be desirable to deflect load from the database |
| Database Read Overload | When many readers simultaneously request the same data element it is called the "Thundering Herd" problem. How to prevent it in a single jvm or clustered configuration |
| Database Write Overload | Writing to the Database is a Bottleneck. Configure write-behind to offload database writes. |
| Caching methods with Spring Annotations | Adding caching to methods using Ehcache Annotations for Spring project |
| Cache Wrapper | A simple class to make accessing Ehcache easier for simple use cases |
All usages of Ehcache start with the creation of a CacheManager.
As of ehcache-1.2, Ehcache CacheManagers can be created as either singletons (use the create factory method) or instances (use new).
Create a singleton CacheManager using defaults, then list caches.
CacheManager.create(); String[] cacheNames = CacheManager.getInstance().getCacheNames();
Create a CacheManager instance using defaults, then list caches.
CacheManager manager = new CacheManager(); String[] cacheNames = manager.getCacheNames();
Create two CacheManagers, each with a different configuration, and list the caches in each.
CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();When the CacheManager is created it creates caches found in the configuration.
Create a CacheManager using defaults. Ehcache will look for ehcache.xml in the classpath.
CacheManager manager = new CacheManager();
Create a CacheManager specifying the path of a configuration file.
CacheManager manager = new CacheManager("src/config/ehcache.xml");Create a CacheManager from a configuration resource in the classpath.
URL url = getClass().getResource("/anotherconfigurationname.xml");
CacheManager manager = new CacheManager(url);Create a CacheManager from a configuration in an InputStream.
InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());
try {
CacheManager manager = new CacheManager(fis);
} finally {
fis.close();
}You are not just stuck with the caches that were placed in the configuration. You can create and remove them programmatically.
Add a cache using defaults, then use it. The following example creates a cache called testCache, which will be configured using defaultCache from the configuration.
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have been added to a CacheManager.
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
manager.addCache(memoryOnlyCache);
Cache test = singletonManager.getCache("testCache");See the cache constructor for the full parameters for a new Cache:
Remove cache called sampleCache1
CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");Ehcache should be shutdown after use. It does have a shutdown hook, but it is best practice to shut it down in your code.
Shutdown the singleton CacheManager
CacheManager.getInstance().shutdown();
Shutdown a CacheManager instance, assuming you have a reference to the CacheManager called manager
manager.shutdown();
See the CacheManagerTest for more examples.
A new cache with a given name can be created from defaults very simply:
manager.addCache(cache name);
The configuration for a Cache can be specified programmatically as an argument to the Cache constructor:
public Cache(CacheConfiguration cacheConfiguration) {
...
}Here is an example which creates a cache called test.
//Create a CacheManager using defaults
CacheManager manager = CacheManager.create();
//Create a Cache specifying its configuration.
Cache testCache = new Cache(
new CacheConfiguration("test", maxElements)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
.overflowToDisk(true)
.eternal(false)
.timeToLiveSeconds(60)
.timeToIdleSeconds(30)
.diskPersistent(false)
.diskExpiryThreadIntervalSeconds(0));
manager.addCache(cache);Once the cache is created, add it to the list of caches managed by the CacheManager:
manager.addCache(testCache);
The cache is not usable until it has been added.
All of these examples refer to manager, which is a reference to a CacheManager, which has a cache in it called sampleCache1.
Obtain a Cache called "sampleCache1", which has been preconfigured in the configuration file
Cache cache = manager.getCache("sampleCache1");Put an element into a cache
Cache cache = manager.getCache("sampleCache1");
Element element = new Element("key1", "value1");
cache.put(element);Update an element in a cache. Even though cache.put() is used, Ehcache knows there is an existing element, and considers the put an update for the purpose of notifying cache listeners.
Cache cache = manager.getCache("sampleCache1");
cache.put(new Element("key1", "value1"));
//This updates the entry for "key1"
cache.put(new Element("key1", "value2"));Get a Serializable value from an element in a cache with a key of "key1".
Cache cache = manager.getCache("sampleCache1");
Element element = cache.get("key1");
Serializable value = element.getValue();Get a NonSerializable value from an element in a cache with a key of "key1".
Cache cache = manager.getCache("sampleCache1");
Element element = cache.get("key1");
Object value = element.getObjectValue();Remove an element from a cache with a key of "key1".
Cache cache = manager.getCache("sampleCache1");
cache.remove("key1");sampleCache1 has a persistent diskStore. We wish to ensure that the data and index are written immediately.
Cache cache = manager.getCache("sampleCache1");
cache.flush();Get the number of elements currently in the Cache.
Cache cache = manager.getCache("sampleCache1");
int elementsInMemory = cache.getSize();Get the number of elements currently in the MemoryStore.
Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getMemoryStoreSize();Get the number of elements currently in the DiskStore.
Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getDiskStoreSize();These methods are useful for tuning cache configurations.
Get the number of times requested items were found in the cache. i.e. cache hits
Cache cache = manager.getCache("sampleCache1");
int hits = cache.getHitCount();Get the number of times requested items were found in the MemoryStore of the cache.
Cache cache = manager.getCache("sampleCache1");
int hits = cache.getMemoryStoreHitCount();Get the number of times requested items were found in the DiskStore of the cache.
Cache cache = manager.getCache("sampleCache1");
int hits = cache.getDiskStoreCount();Get the number of times requested items were not found in the cache. i.e. cache misses.
Cache cache = manager.getCache("sampleCache1");
int hits = cache.getMissCountNotFound();Get the number of times requested items were not found in the cache due to expiry of the elements.
Cache cache = manager.getCache("sampleCache1");
int hits = cache.getMissCountExpired();These are just the most commonly used methods. See CacheTest for more examples. See Cache for the full API.
This example shows how to dynamically modify the cache configuration of an already running cache:
Cache cache = manager.getCache("sampleCache");
CacheConfiguration config = cache.getCacheConfiguration();
config.setTimeToIdleSeconds(60);
config.setTimeToLiveSeconds(120);
config.setMaxElementsInMemory(10000);
config.setMaxElementsOnDisk(1000000);Dynamic cache configurations can also be frozen to prevent future changes:
Cache cache = manager.getCache("sampleCache");
cache.disableDynamicFeatures();A cache will automatically participate in the ongoing UserTransaction when configured in transactionalMode XA. This can be done programmatically:
//Create a CacheManager using defaults
CacheManager manager = CacheManager.create();
//Create a Cache specifying its configuration.
Cache xaCache = new Cache(
new CacheConfiguration("test", 1000)
.overflowToDisk(true)
.eternal(false)
.transactionalMode(CacheConfiguration.TransactionalMode.XA)
.terracotta(new TerracottaConfiguration().clustered(true)));
manager.addCache(xaCache);Or in your CacheManager's configuration file :
<cache name="xaCache"
maxElementsInMemory="500"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="1"
transactionalMode="xa">
<terracotta clustered="true"/>
</cache>Please note that XA Transactional caches are currently only supported when clustered with Terracotta.
The Cache can then be used without any special requirement. Changes will only become visible to others, once the transaction has been committed.
Ehcache cache = cacheManager.getEhcache("xaCache");
transactionManager.begin();
try {
Element e = cache.get(key);
Object result = complexeService.doStuff(element.getValue());
// This put will be rolled back should complexeService.doMoreStuff throw an Exception
cache.put(new Element(key, result));
// Any changes to result in that call, will be visible to others when the Transaction commits
complexeService.doMoreStuff(result);
transactionManager.commit();
} catch (Exception e) {
transactionManager.rollback();
}See the fully worked examples in the Terracotta Clustering Chapter.
This example shows how to register CacheStatistics in the JDK1.5 platform MBeanServer, which works with the JConsole management agent.
CacheManager manager = new CacheManager();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);See the examples in the JCache Chapter.
See the examples in the Cache Server Chapter.
Ehcache comes with a comprehensive JUnit test suite, which not only tests the code, but shows you how to use ehcache.
A link to browsable unit test source code for the major Ehcache classes is given per section. The unit tests are also in the src.zip in the Ehcache tarball.