Using Ehcache SampledCache

SampledCache is an implementation of CachedMBean and exposes Cache Statistics. It's a Cache decorator for getting statistics for a Cache. It's fairly simple to use, let see a quick sample

The complete code can be found at EhcacheStatsDemo.java

public static void ehCacheStatsDemo() throws NotCompliantMBeanException {
    CacheManager cacheManager = CacheManager.newInstance();
    Ehcache cache = cacheManager.addCacheIfAbsent("testCache");
    SampledCache sampledCache = new SampledCache(cache);

    for (int i = 0; i < 100; i++) {
      Element element = new Element("Key-"+i, "Value-"+i);
      cache.put(element);
    }

    for (int i = 0; i < 100; i++) {
      cache.get("Key-" + 1);
    }
    System.out.println(sampledCache.getPutCount());
    System.out.println(sampledCache.getCacheMissCount());
    System.out.println(sampledCache.getCacheHitCount());
    cacheManager.shutdown();
  }

To use SampledCache, you pass the backing caching during construction (as shown in Line# 4). Using the SampledCache, you can view the stats of the backing cache, cache in the example above.

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.