Multiple threads calling the @Cacheable method. Spring cache (3.2.6) is allowing all threads into the method
caching, java, multithreading, spring
Solution
what you want is `@Cacheable(sync = true)`
Problem
I have a DAO object with a method of the following type. I have injected the DAO into service layer and I'm able to get cached results from this DAO method call. But when multiple threads invoke this method (on a proxy that wraps the DAO singleton) some of those threads still going to fetch the data from my database i.e., the fetchDataFromDb() method call is still executed. Is there a way to get around this? Is this a Spring caching bug? ``` @Override @Cacheable(value = "CacheName") public Map<String, DomainObject> fetchDataFromDb() { .... } ``` Following XML configuration of my Spring application context file. This is a web application. I simulated the multiple threads using JMeter. ``` <cache:annotation-driven /> <!-- generic cache manager --> <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="CacheName" /> </set> </property> </bean> ```