Ehcache cache size at runtime

ehcache, java

Solution

Yes, using Ehcache, you can configure your caches and retrieve their sizes by Java code only (no XML config). The exact way to integrate everything depends on your specific architecture; I'm going to assume Jersey for doing API stuff and Guice for dependency injection.

Defining your cache

Make your cache manager available via dependency injection. This can be done via a Guice module:

@Provides
@Singleton
CacheManager provideCacheManager() {
  CacheManager cacheManager = CacheManager.create();

  /* very basic cache configuration */
  CacheConfiguration config = new CacheConfiguration("mycache", 100)
    .timeToLiveSeconds(60)
    .timeToIdleSeconds(30)
    .statistics(true);

  Cache myCache = new Cache(config);
  cacheManager.addCacheIfAbsent(myCache);

  return cacheManager;
}

Notice that statistics is turned on for `mycache`.

Again, using your cache can be done entirely in Java code but depends on your architecture and design. Typically I do this using method interception (via AOP) but that's another topic.

Fetch cache stats via REST API

Given your `CacheManager` is available via dependency injection you can then wire it up to a REST endpoint and allow access to cache statistics:

@Path("stats")
@Produces("text/plain")
public class StatsResource {
  @Inject private CacheManager cacheManager;

  @GET
  public String stats() {
    StringBuffer sb = StringBuffer();

    /* get stats for all known caches */
    for (String name : cacheManager.getCacheNames()) {
      Cache cache = cacheManager.getCache(name);
      Statistics stats = cache.getStatistics();

      sb.append(String.format("%s: %s objects, %s hits, %s misses\n",
        name,
        stats.getObjectCount(),
        stats.getCacheHits(),
        stats.getCacheMisses()
      ));
    }
    return sb.toString();
  }
}

Now you can fetch information about your caches by REST call:

GET /stats

HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8

mycache: 8 objects, 59 hits, 12 misses

What about JMX?

Ehcache makes it easy to register your cache manger with an MBean server. It can be done in Java code. Update your Guice module, registering your `cacheManager` to the system `MBeanServer`:

MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(cacheManager, mBeanServer, false, false, false, true);

Now you can attach JConsole to your Java process and find your cache statistics in the MBean `net.sf.ehcache.CacheStatistics`.

Problem

I am running a large VM in production and would like to understand more about my cache size at runtime. My caches are all based upon ehache What is the best way to see the size of individual caches at runtime. Either using JMX or API Is there any option to configure by plain-old-java calls to the CacheManager, or (ignoring JMX for the moment) must one build the XML configuration slug up in a big string?

Original source