Spring cacheable not synchronized

ianaz picture ianaz · Mar 5, 2015 · Viewed 9.8k times · Source

I have a singleton class (@Service annotated). This class has a method which takes 200/300ms to execute.

This method is annotated with @Cacheable and synchronized.

@Cacheable(value="nextPlaying", key = "#startingFrom.getYear() + #startingFrom.getMonth() + #startingFrom.getDay() + #startingFrom.getHours() + #startingFrom.getMinutes() + #locale.getLanguage()")
public synchronized List<Match> getNextPlaying(Date startingFrom, Locale locale)

By launching multiple threads calling this method I see that for these 200/300ms until the result isn't cached, it executes again and again the method until is cached. Seems that @Cacheable annotation doesn't take synchronized into account... Is this a bug?

Answer

Clement.Xu picture Clement.Xu · Sep 12, 2016

Good news, spring framework 4.3 has provided a way to support your need, by adding sync=true in @Cacheable.