java 38 lines · 7 steps

Warming a Spring cache at startup

A Spring bean pre-loads a cache once all singletons are ready, so the first real request doesn't pay the cold-start cost.

Explained by highlit
1@Component
2public class RegionCacheWarmer implements SmartInitializingSingleton {
3 
4 private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);
5 
6 private final RegionService regionService;
7 private final CacheManager cacheManager;
8 
9 public RegionCacheWarmer(RegionService regionService, CacheManager cacheManager) {
10 this.regionService = regionService;
11 this.cacheManager = cacheManager;
12 }
13 
14 @Override
15 public void afterSingletonsInstantiated() {
16 Cache cache = cacheManager.getCache("regions");
17 if (cache == null) {
18 log.warn("Cache 'regions' is not configured; skipping warm-up");
19 return;
20 }
21 
22 StopWatch watch = new StopWatch();
23 watch.start();
24 
25 List<String> codes = regionService.findActiveRegionCodes();
26 for (String code : codes) {
27 try {
28 regionService.getRegionByCode(code);
29 } catch (Exception ex) {
30 log.error("Failed to warm cache entry for region '{}'", code, ex);
31 }
32 }
33 
34 watch.stop();
35 log.info("Warmed 'regions' cache with {} entries in {} ms",
36 codes.size(), watch.getTotalTimeMillis());
37 }
38}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1SmartInitializingSingleton runs code after the whole context is built, making it ideal for cross-bean startup tasks.
  2. 2Guarding against a missing cache lets warm-up degrade gracefully instead of crashing the application.
  3. 3Isolating each entry's fetch in a try/catch keeps one bad record from aborting the entire warm-up.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Warming a Spring cache at startup — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code