Card 02/ 07
All 7 cards
ComparisonDifficulty: Intermediate1 min
@Cacheable, @CachePut, @CacheEvict
Three annotations, three different relationships between the method call and the cache.
@CachePut(value = "fares", key = "#zone")
double updateFare(String zone, double newFare) {
// always runs, then overwrites the cache entry with the result
return newFare;
}
@CacheEvict(value = "fares", key = "#zone")
void evictFare(String zone) {
// removes the entry; nothing to return
}@CachePut always ran (count=1), lookupFare now returns cached: 15.0
after @CacheEvict, lookupFare ran again: 1 time(s)| Annotation | Does |
|---|---|
@Cacheable | Skips the method if the cache already has an entry for these arguments |
@CachePut | Always runs the method, then stores the result — never skips |
@CacheEvict | Removes an entry, so the next @Cacheable call has to run for real |
@Cacheable is for reads you're willing to skip. @CachePut is for a write that should also refresh what a read would see — updating a fare and making sure the cache reflects the new value, in one call. @CacheEvict is for a write that should just invalidate what's there, with nothing to put back yet.