Card 02/ 07

ComparisonDifficulty: Intermediate1 min

@Cacheable, @CachePut, @CacheEvict

Three annotations, three different relationships between the method call and the cache.

java
@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
}
text
@CachePut always ran (count=1), lookupFare now returns cached: 15.0
after @CacheEvict, lookupFare ran again: 1 time(s)
run in a container — @CachePut updates without skipping; @CacheEvict removes, forcing the next call to run for real
The three annotations
AnnotationDoes
@CacheableSkips the method if the cache already has an entry for these arguments
@CachePutAlways runs the method, then stores the result — never skips
@CacheEvictRemoves 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.