The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Architecture and operations
What is a cache, and what do you gain and lose by using one?
Why it exists — If something that takes time, such as a database query or a call to another server, is done again for every request even though the same answer is known to come out, the user waits every time and the same work piles up on the original source. A cache keeps an answer, once obtained, in a place from which it can be fetched quickly and reuses it, so that slow work is not repeated. In return, when the original changes, you have to separately take care of when to discard the value in the cache.
Where it's used today — Things that are read often but change rarely, such as product information, category lists, and settings, are put in a cache. In Spring, you write @EnableCaching on a configuration class, @Cacheable on a method that looks something up, and @CacheEvict on a method that changes the value. Where the cache is kept is chosen with a CacheManager bean, and the same annotations work from the memory of a single server to Redis, which several servers look at together. Things that must always have the current value, such as remaining stock or an account balance, are not put in a cache, or the value in the cache is deleted immediately when the value changes.
A cache is a device that writes down a result that took a long time to get, in a place close by, and hands out what it wrote down when the same thing is asked for again, without going to the source. A cache is not the source. It is a copy of the value from the moment it was read from the source, so after the source changes, it can hand out an old value. In Spring you do not write the cache yourself. You write annotations that Spring provides. In the code on the screen, @EnableCaching on the CacheConfig class turns the caching feature on, and the ConcurrentMapCacheManager registered with @Bean (a class provided by Spring) keeps a cache named product in memory. If you write @Cacheable("product") above the find method of ProductService (an example class we made), Spring looks at the product cache around the call to find and writes down the result. The body of find reads the value from the source (a Map that stands in for a database) and counts the reads from the source with loadCount. The lab does not measure real time. It shows "how many times the slow work was done" by the number of reads from the source. Caller (an example class we made) looks up product 1 twice with the ProductService bean that Spring supplied. You can remove the @Cacheable line, change the source with rename between the two lookups, or write @CacheEvict above rename, and you see how many times the source is read and whether the second value you receive is the same as the source. The last question compares what @Cacheable does with a version written by hand with a Map.
Checked against real execution · Compiled nine combinations with the same source as the screen on Spring Framework 7.0.9 (spring-context, @EnableCaching + ConcurrentMapCacheManager) and JDK 21, ran them, and checked the output, whether a proxy exists, and the values written in the cache at each step
// Turn the caching feature on: @Cacheable and @CacheEvict work only with this setting
@Configuration
@EnableCaching
class CacheConfig {
// Where the cache is kept: ConcurrentMapCacheManager, provided by Spring (it uses a Map in memory)
@Bean
CacheManager cacheManager() {
return new ConcurrentMapCacheManager("product");
}
}
// An example product service we made
@Service
class ProductService {
// The source: the original values of product names (a Map that stands in for a database)
private final Map<Long, String> db = new HashMap<>(Map.of(1L, "keyboard"));
// How many times the source was read
private int loadCount = 0;
// Writes the result in the product cache by id. If called again with the same id, the body does not run
@Cacheable("product")
public String find(Long id) {
// Read from the source (in real code, this is where slow work such as a database query goes)
loadCount++;
return db.get(id);
}
public void rename(Long id, String name) {
db.put(id, name);
}
public int loadCount() {
return loadCount;
}
public String source(Long id) {
return db.get(id);
}
}
// An example class we made that calls ProductService
@Component
class Caller {
@Autowired
ProductService productService;
void run() {
// Look up product 1 for the first time
productService.find(1L);
// Look up product 1 again
String second = productService.find(1L);
// Reads from the source / second value received / value in the source
System.out.println(
productService.loadCount() + " / " + second + " / " + productService.source(1L));
}
}
We checked Spring Framework 7.0.9 (spring-context) by running it on JDK 21.0.12.1. All nine combinations (three ways of putting a cache on find times three things that can happen between the two lookups) were checked in the same way. The source is the same as the code on the screen (only the package and import lines and measurement lines marked with PROBE at the end were added). It was compiled with javac (with -parameters turned on; the build settings of Spring Boot also turn this on), and a new Java process was started for each combination. The classes on the screen were found by AnnotationConfigApplicationContext through component scanning, and the checking program called run() of the Caller bean and captured the line that run() printed. What was compared is the three printed values (the number of reads from the source, the value the second find returned, and the value in the source). As facts that the step sentences rely on, we also checked the class of the ProductService bean (the ProductService$SpringCGLIB$0 proxy when find has @Cacheable or rename has @CacheEvict, and plain ProductService when neither is there or when the cache is written by hand), whether the object that Caller received is that bean, and loadCount and what was written in the cache after the first find, after rename, and at the end (for Spring, the product cache of the CacheManager, and for the hand-written version, the Map in the cache field). As a variation that is not on the screen, we also ran @CacheEvict("product") with no key above rename, and in that case the value for key 1 in the product cache was not erased and the second find received "keyboard" (because the key becomes both parameters used together). That ConcurrentMapCacheManager has no method that sets a validity time was checked by opening the public methods of this class with javap. Nothing was shortened in the code on the screen. This lab was run with only spring-context, without Spring Boot, and the setting with which Boot creates a CacheManager automatically was not verified. Reading from the source does not really take long and no time was measured, and "slow" is shown only by the number of reads from the source. For the documentation, we followed what we had confirmed earlier, and did not open it again this time: the Spring Framework Reference, Cache Abstraction section (https://docs.spring.io/spring-framework/reference/integration/cache/strategies.html; if the method was already called with the same arguments, it returns the cached result without executing the method) and RFC 9111 (HTTP Caching) section 4.2 (a stored response that is past its freshness lifetime is called stale). Not covered: calling find from inside the same class so that it does not pass through the proxy and the cache is not used, a null result, @CachePut, a cache that several threads write at the same time, what to throw away when the cache is full, the validity time (TTL), many requests rushing to the source when a popular value disappears all at once, the HTTP cache between a browser and a server (ETag), and Redis. These are covered in the in-depth labs "Cache abstraction", "Caching and TTL", "HTTP caching and ETag", and "Redis single-threaded execution".
Previous lab: Load balancers · Next lab: Message queues
Struck-through text was removed from the first version of the code; highlighted text was added.