Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple threads calling the @Cacheable method. Spring cache (3.2.6) is allowing all threads into the method

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>

like image 941
Sai Dubbaka Avatar asked Jan 30 '14 21:01

Sai Dubbaka


People also ask

Why is caching not working?

Here are some ways you can try to fix your caching problem, in order of escalation: Try holding down the Shift key while pressing the Refresh button. Close your browser and re-open it (make sure you are NOT on the cached page) and delete your temporary Internet files (clear your cache).

How do I evict multiple caches in spring?

Spring provides two ways to evict a cache, either by using the @CacheEvict annotation on a method, or by auto-wiring the CacheManger and clearing it by calling the clear() method.

How do I enable caching in spring?

To enable the Spring Boot caching feature, you need to add the @EnableCaching annotation to any of your classes annotated with @Configuration or to the boot application class annotated with @SpringBootApplication .


1 Answers

what you want is @Cacheable(sync = true)

like image 74
70kg Avatar answered Oct 07 '22 14:10

70kg