Tips&Tricks: Ehcache post processing method cached results
Posted by Jai on October 31, 2012
The post is to share a tip on advisory for not post processing the cached results from Ehcache method interceptor. In case you are using method cache interceptor within you application, please make sure the cached results are not updated anywhere after retrieving data from cache.
An example of how you can use spring aop method interceptor for caching the results of a method, Caching the result of methods using Spring and EHCache
Let us take an example,
List com.jai.test.TestService.getTestList();
public class TestObj implements Serializable
{
...
private List customers;
...
}
We have getTestList() method cached using method interceptor and refresh time of 5 minutes.
<cache name="test.methodcache" maxElementsInMemory="200000" overflowToDisk="false" diskPersistent="false" eternal="false" timeToLiveSeconds="300" /> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation"> <value>classpath:ehcache-services.xml</value> </property> </bean> <bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <ref local="cacheManager" /> </property> <property name="cacheName"> <value>test.methodcache</value> </property> </bean> <bean id="methodCacheInterceptor" class="com.jai.test.MethodCacheInterceptor"> <property name="cache"> <ref local="methodCache" /> </property> <property name="methodCacheEnabled"> <value>true</value> </property> </bean>
Add point cuts to service method,
<aop:pointcut id="testService.getTestList" expression="execution(* com.jai.test.TestService.getTestList(..))" /> <aop:advisor pointcut-ref="testService.getTestList" advice-ref="methodCacheInterceptor"/>
Now you will retrieve results from cache, but couple of points you need to make sure while using method caching.
NO post processing for cached results
Make sure that the method getTestList() called from different places do not update the results. The referenced object in the list should not be updated from anywhere in the calling places. Otherwise the cached results data itself is updated and the clients will see different state of data from cached time data.
Avoid hibernate lazy initialization errors
If you application is also using hibernate and the collection customers is lazy loaded, while accessing TestObj.getCustomers() will throw error. You need to make sure, either you load dependent data non lazy way or use opensessionviewfilter to aovid lazy initialization errors.
Using method caching is very tricky, it can be both helpful in providing performance benefits and also dangerous to debug problems.

