Search code examples
javaehcache

How do I get the number of objects in an Ehcache?


I am using Ehcache 2.10.4. I configure my cache like this using an enum:

FAILED_MESSAGES_REPLAY_COUNTS("msgreplaycount", 50000, false, 0, 3600)

private TmaticInMemoryCache(String name, int maxElementsInMemory, boolean eternal, int timeToLiveSeconds, int timeToIdleSeconds) {
    this.cacheName = name;
    CacheManager cm = CacheManager.getInstance();
    if (!cm.cacheExists(name)) {// overflowtoDisk is always false
        cm.addCache(new Cache(name, maxElementsInMemory, false, eternal, timeToLiveSeconds, timeToIdleSeconds));
        this.theCache = cm.getCache(this.cacheName);
    }
}

But when I check the size, it never seems to evict/expire anything.

public static String cacheStats() {
    StringBuilder sb = new StringBuilder("Storm in memory caches:");
    for (int i = 0; i < TmaticInMemoryCache.values().length; i++) {
        TmaticInMemoryCache tmaticCache = TmaticInMemoryCache.values()[i];
        sb.append("\n  *  ").append(tmaticCache.name()).append(":");
        Cache c = tmaticCache.getCache();
        StatisticsGateway statistics = c.getStatistics();
        long hits = statistics.cacheHitCount();
        long misses = statistics.cacheMissCount();
        long size = statistics.getSize();
        long expired = statistics.cacheExpiredCount();
        long evicted = statistics.cacheEvictedCount();
        sb.append(String.format("(hits/misses: %d/%d, expired/evicted: %d/%d, current size: %d)", hits, misses, expired, evicted, size));
    }
    return sb.toString();
}

So this is the result after a few days of not running (jvm is idle). Ehcache reports that there are still 317 items in the cache, but nothing has been expired.

FAILED_MESSAGES_REPLAY_COUNTS:(hits/misses: 4/13665103, expired/evicted: 0/0, current size: 317)

These items should only stay in the cache for 300 seconds but they seem to stay forever.


Solution

    • Your setup uses TTI and not TTL, that means that each time you hit an entry, its expiry is postponed by the amount configured.
    • From the statistics printed out at the bottom, you have a very low hit ratio compared to the misses. Which means you pretty much never read a value from the cache
    • Ehcache does not have an eager expiry mechanism. Expired entries in the cache will remain there until they are requested (and thus cleaned up) or until the cache is full and eviction kicks in.

    From these points, the numbers you are seeing make sense: the few entries you hit see their lifespan extended, the other entries just sit there, most likely invalid by now but never cleaned up and eviction is not a problem because you are way below capacity.

    And finally, you answer yourself your question since you can display the number of elements in the cache.