Monday, December 30, 2013

Ehcache: Java's Most Widely-Used Cache

Ehcache is an open source, standards-based cache for boosting performance, offloading your database, and simplifying scalability. It's the most widely-used Java-based cache because it's robust, proven, and full-featured. Ehcache scales from in-process, with one or more nodes, all the way to mixed in-process/out-of-process configurations with terabyte-sized caches.
Terracotta actively develops, maintains, and supports Ehcache as a professional open source project available under an Apache 2 license. In addition to the open source Ehcache edition, Terracotta offers BigMemory for enterprise-grade in-memory data management with high availability, worldwide 24x7 professional support, consulting, and training services.
For applications requiring a coherent distributed cache, use Terracotta BigMemory Max, which is available in both free and full versions. (Terracotta no longer actively updates the open-source version of Terracotta Server Array, also known as Terracotta. However, you can still download the latest open-source version of Terrcotta Server Array.)
http://ehcache.org/documentation/code-samples

Code Samples

Introduction

The Code Samples page contains examples that will help you get started with Ehcache.
If you have suggestions or ideas for more code samples, please tell us about them using the forums or mailing list.

Using the CacheManager

All usages of Ehcache start with the creation of a CacheManager. See Key Classes and Methods for details on how to create CacheManagers.

Singleton versus Instance

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.newInstance();
String[] cacheNames = manager.getCacheNames();
Create two CacheManagers, each with a different configuration, and list the caches in each.
CacheManager manager1 = CacheManager.newInstance("src/config/ehcache1.xml");
CacheManager manager2 = CacheManager.newInstance("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();

Ways of loading Cache Configuration

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 = CacheManager.newInstance();
Create a CacheManager specifying the path of a configuration file.
CacheManager manager = CacheManager.newInstance("src/config/ehcache.xml");
Create a CacheManager from a configuration resource in the classpath.
URL url = getClass().getResource("/anotherconfigurationname.xml");
CacheManager manager = CacheManager.newInstance(url);
Create a CacheManager from a configuration in an InputStream.
InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());
try {
  CacheManager manager = CacheManager.newInstance(fis);
} finally {
  fis.close();
}

Adding and Removing Caches Programmatically

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 , 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);
singletonManager.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");

Shutdown the CacheManager

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.shutdown();
See the CacheManagerTest for more examples.

Creating Caches Programmatically

Creating a new cache from defaults

A new cache with a given name can be created from defaults very simply:
manager.addCache(cacheName);

Creating a new cache with custom parameters

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 "testCache."
//Create a singleton CacheManager using defaults
CacheManager manager = CacheManager.create();

//Create a Cache specifying its configuration.
Cache testCache = new Cache(
  new CacheConfiguration("testCache", maxEntriesLocalHeap)
    .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
    .eternal(false)
    .timeToLiveSeconds(60)
    .timeToIdleSeconds(30)
    .diskExpiryThreadIntervalSeconds(0)
    .persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP)));
  manager.addCache(testCache);
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.

Using Caches

All of these examples refer to , which is a reference to a CacheManager, which has a cache in it called .

Obtaining a reference to a Cache {#Obtaining a reference to a Cache}

Obtain a Cache called "sampleCache1", which has been preconfigured in the configuration file
Cache cache = manager.getCache("sampleCache1");

Performing CRUD operations

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");

Obtaining Cache Sizes

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();

Obtaining Statistics of Cache Hits and Misses

These methods are useful for tuning cache configurations. Get the number of times requested items were found in the cache (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 (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.

Dynamically Modifying Cache Configurations

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.setMaxEntriesLocalHeap(10000);
config.setMaxEntriesLocalDisk(1000000);
Dynamic cache configurations can also be frozen to prevent future changes:
Cache cache = manager.getCache("sampleCache");
cache.disableDynamicFeatures();

Transactions

A cache will automatically participate in the ongoing UserTransaction when configured in transactionalMode XA.
Note that XA Transactional caches are supported only for local Ehcache, BigMemory Go, and BigMemory Max. Replicated Ehcache architectures such as RMI, JMS, or JGroups are not supported as there is no locking in those architectures.

Cache Statistics and Monitoring

Registering CacheStatistics in an MBeanServer

This example shows how to register CacheStatistics in the JDK1.5 platform MBeanServer, which works with the JConsole management agent.
CacheManager manager = CacheManager.newInstance();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);

More examples

JCache Examples

See the examples in JCache.

Cache Server Examples

See the examples in Cache Server.

Browse the JUnit Tests

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.

6 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Java Course in Chennai

raybanoutlet001 said...

adidas tubular x
true religion jeans
ray ban sunglasses outlet
tiffany and co jewelry
tiffany and co uk
mlb jerseys shop
chrome hearts online store
yeezy
chrome hearts online
yeezy boost 350
http://www.chromehearts.com.co
adidas yeezy uk
louboutin shoes
michael kors outlet
cheap oakley sunglasses
http://www.nikedunks.us.org
retro jordans
ralph lauren uk
michael jordan shoes
toms outlet store
yeezy boost
tiffany and co uk