Johan Sjöberg
Johan Sjöberg

Reputation: 49187

Incorrect ehcache statistics: hits+misses == 0

I have a problem where net.sf.ehcache.CacheManager appears returns invalid statistics.

I'm using ehcache-core v2.3.2 (latest version) with ehcache-spring-annotations.

The problem is that getMemoryStoreObjectCount returns 1 object while both getCacheHits and getCacheMisses returns 0. Isn't the total count supposed to be hits + misses ?

The unit test below should illustrate the problem (it's applied to an empty database):

@Test
public void testCache() {
    Entity e = ..
    dao.storeEntity(e);
    dao.getEntity(e);
    assertEquals(1, cache.getStatistics().getMemoryStoreObjectCount()); // ok
    assertEquals(0, cache.getStatistics().getCacheHits()); // ok
    assertEquals(1, cache.getStatistics().getCacheMisses()); // fails due to 0

}

For completeness I include all essential configuration:

Spring config

<ehcache:annotation-driven cache-manager="ehCacheManager" />
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml"/>
</bean>

ehcache.xml

<ehcache>
     <defaultCache eternal="false" maxElementsInMemory="1000"
        overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
        timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

dao

@Cacheable(keyGenerator=@KeyGenerator(name="StringCacheKeyGenerator"))
public Entity getEntity(Serializable key) {
    return // sql ... 
}

Upvotes: 13

Views: 6889

Answers (3)

Ross Bu
Ross Bu

Reputation: 103

The <defaultCache ... statistics="true" /> works greatly in contrast with the old way cache.setStatisticsEnabled(true); that needs the lower version of ehcache (core and etc).

Upvotes: 5

aaronvargas
aaronvargas

Reputation: 14142

Add statistics="true" to your ehcache.xml, it's usually better to keep your configuration changes outside your code.

<ehcache>
     <defaultCache ... statistics="true" />
...
</ehcache>

Upvotes: 17

Johan Sj&#246;berg
Johan Sj&#246;berg

Reputation: 49187

Found the solution to the problem by setting the following properties in net.sf.ehcache.hibernate.EhCache:

  cache.setStatisticsEnabled(true);
  cache.setStatisticsAccuracy(Statistics.STATISTICS_ACCURACY_GUARANTEED);

Upvotes: 16

Related Questions