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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1SmartInitializingSingleton runs code after the whole context is built, making it ideal for cross-bean startup tasks.
- 2Guarding against a missing cache lets warm-up degrade gracefully instead of crashing the application.
- 3Isolating each entry's fetch in a try/catch keeps one bad record from aborting the entire warm-up.
Related explainers
java
public final class EmailNormalizer { private static final Pattern EMAIL_PATTERN = Pattern.compile( "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
Normalizing email addresses in Java
validation
regex
normalization
Intermediate
8 steps
ruby
module UniqueJob extend ActiveSupport::Concern class_methods do
Deduplicating Active Job enqueues in Rails
concurrency
idempotency
caching
Advanced
9 steps
python
from datetime import date, timedelta from typing import Annotated from fastapi import APIRouter, Depends, Query
Validating date ranges with FastAPI dependencies
dependency-injection
validation
pydantic
Intermediate
6 steps
java
@RestController @RequestMapping("/api/products") @RequiredArgsConstructor public class ProductBatchController {
Batch JSON Merge Patch in Spring
json-merge-patch
rest-api
partial-update
Intermediate
8 steps
java
public class TimedFetchService { private final ExecutorService executor = Executors.newFixedThreadPool(8); private final HttpClient httpClient = HttpClient.newHttpClient();
Enforcing HTTP timeouts with a Future
concurrency
timeouts
thread-pool
Intermediate
8 steps
java
@Component public class RefreshTokenSuccessHandler implements AuthenticationSuccessHandler { private final RefreshTokenService refreshTokenService;
Issuing JWT and refresh tokens on login in Spring
authentication
jwt
http-cookies
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/warming-a-spring-cache-at-startup-explained-java-8480/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.