mike27
mike27

Reputation: 975

Concurrent calls to cached method

I'm using Spring cache abstraction with Guava cache. I have a method with @Cacheable annotation and parameter (that serves as a cache key) to put values into the cache. But this method is accessed in a multi threaded env so there are multiple concurrent calls to the method with the same parameter value. So that means the same logic that creates the value to be cached is done for the same cache key multiple times and put into the cache multiple times concurrently. It'd be much more efficient if for each parameter value (cache key) the method would be called only once and put into the cache once. Can Spring handle such a scenario?

Upvotes: 3

Views: 2263

Answers (2)

KarthikaSrinivasan
KarthikaSrinivasan

Reputation: 599

In a multi-threaded environment, certain operations might be concurrently invoked for the same argument (typically on startup). By default, the cache abstraction does not lock anything, and the same value may be computed several times, defeating the purpose of caching.

For those particular cases, you can use the sync attribute to instruct the underlying cache provider to lock the cache entry while the value is being computed. As a result, only one thread is busy computing the value, while the others are blocked until the entry is updated in the cache. The following example shows how to use the sync attribute:

@Cacheable(cacheNames="foos", sync=true) public Foo executeExpensiveOperation(String id) {...}

By Deafult sync value will be false

Upvotes: 0

Stephane Nicoll
Stephane Nicoll

Reputation: 33121

As of Spring Framework 4.3 (still in early development phase at the time of writing) a new flag on @Cacheable called sync is available. If you enable that flag, you opt-in for basically what you're asking.

Spring Framework 4.3 GA is due around May next year but you should see a first milestone in Q1 2016 still. Please give that a try and let us know if that works for you.

Upvotes: 5

Related Questions