java / intermediate
Snippet
Tuning Caffeine In-Memory Cache Eviction Within Spring CacheManager
Spring's Cache abstraction integrates with high-performance Caffeine caching to manage memory utilization under high-throughput workloads. Configuring maximumSize activates W-TinyLFU eviction algorithms, bounding memory growth and preventing heap exhaustion from continuous key generation, while expireAfterWrite ensures time-based data freshness.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Configuration@EnableCachingpublic class CacheConfig {@Beanpublic CacheManager cacheManager() {CaffeineCacheManager cacheManager = new CaffeineCacheManager("productMetrics", "fxRates");cacheManager.setCaffeine(Caffeine.newBuilder().initialCapacity(100).maximumSize(5_000).expireAfterWrite(15, TimeUnit.MINUTES).recordStats());return cacheManager;}}@Servicepublic class ProductService {@Cacheable(value = "productMetrics", key = "#sku", unless = "#result == null")public ProductMetrics fetchMetrics(String sku) {return heavyComputationFromExternalApi(sku);}}
spring
Breakdown
1
cacheManager.setCaffeine(Caffeine.newBuilder()
Defines the Caffeine builder specifications applied to all caches managed by this CacheManager.
2
.maximumSize(5_000)
Imposes a hard threshold on cached item count, triggering automatic entry eviction when full.
3
@Cacheable(value = "productMetrics", key = "#sku", unless = "#result == null")
Interprets cache hit/miss semantics and prevents storing null values in memory via conditional SpEL filtering.