Sub topic 13
Handling concurrent misses with sync=true
This chapter assumes you know how @Cacheable works, how cache keys are built, and how to configure a provider such as Caffeine. It covers what happens when many threads miss the same key at once, and how sync = true addresses it.
The problem: concurrent misses
@Cacheable follows a simple sequence. It checks the cache, and on a miss it calls the method and stores the result. That sequence is not atomic. If 50 requests ask for the same uncached key at the same moment, all 50 can see a miss and all 50 can run the slow method.
This is called a cache stampede (also a thundering herd). It is most harmful right after startup, after an eviction, or when a popular entry expires. The expensive call is the one you were trying to protect, and it now runs many times in parallel.
Using sync = true
Set sync = true on @Cacheable. Spring then calls the provider's get(key, valueLoader) method. The provider makes sure only one thread runs the loader for a given key. Other threads asking for that key block until the value is available.
@Service
public class ExchangeRateService {
@Cacheable(cacheNames = "rates", key = "#currency", sync = true)
public java.math.BigDecimal rateFor(String currency) {
// Imagine a slow remote call here.
return fetchFromRemote(currency);
}
private java.math.BigDecimal fetchFromRemote(String currency) {
return new java.math.BigDecimal("1.08");
}
}The lock is per key. A load for USD does not block a load for EUR.
Restrictions
Because the provider controls the load, sync = true limits what else you can combine with it.
- Use only one cache name. Spring rejects
sync = truewith several caches. - Do not use
unless. The provider decides to store the loaded value, so Spring cannot filter the result afterward. - Do not combine it with other cache operations on the same method, such as
@CachePutor@CacheEvict.
If you need unless = "#result == null", you must choose between that filter and stampede protection. A common workaround is to return an Optional or a wrapper type and let the cache hold the empty value for a short time.
Provider support
Support depends on the cache implementation.
| Provider | Behavior with sync=true |
|---|---|
| Caffeine | Atomic load per key. Other threads wait. |
| Redis (`RedisCache`) | Uses a local lock in the cache object, so protection applies per JVM only. |
| ConcurrentMapCache | Uses `computeIfAbsent`-style loading, so one load per key. |
When to use it
Turn on sync = true when the method is expensive, many callers share a small set of hot keys, and a duplicate load is costly or rate-limited. Skip it for cheap methods. Waiting threads add latency, and a slow or failing loader makes every waiter wait or fail with it.
Exercise
A method is annotated with @Cacheable(cacheNames = "rates", sync = true, unless = "#result == null"). What happens, and what are your options?
Show answer
Spring rejects this combination, because unless cannot be used with sync = true. The application fails when the cache operation is first processed. Either remove unless and accept that a null or empty result may be cached, or drop sync = true and accept possible duplicate loads. You can also return a wrapper such as Optional so the empty result is stored deliberately.
Exercise
Your service runs on four instances sharing one Redis cache, and sync = true is set on a hot method. After the entry expires, how many times can the slow loader run at most at once?
Show answer
Up to four, one per instance. The lock is local to each JVM, so each instance runs the loader once and the others in that instance wait. To limit it further you need a distributed lock or a different refresh strategy.