A lazy cache starts empty and builds as requests arrive, avoiding startup work and memory use for data that may never be needed. section 7.4
Choose the tradeoff against the workload:
- Lazy loading can reduce startup time and unnecessary memory, but the first request for an uncached item pays the loading cost. section 7.4 section 7.4.2
- For larger datasets, use request patterns to inform expiration; percentile-based intervals can help balance cache reuse against memory use. section 7.4
- Set explicit data-size assumptions before choosing: eager loading may be reasonable for a small dictionary, while a very large one changes the risk. section 7.4.2
Listing 7.18 Constructing a word-exists cache
LoadingCache<String, Boolean> wordExistsCache =
CacheBuilder.newBuilder()
.ticker(ticker)
.expireAfterAccess(DEFAULT_EVICTION_TIME).recordStats() #A
.build(
new CacheLoader<String, Boolean>() {
@Override
public Boolean load(@Nullable String word) throws Exception {
if (word == null)
return false; #B
}
return checkIfWordExists(word); #C
}
});A word-existence cache loads a result when requested and configures expiration after access. section 7.4











