0 day streak
java / beginner
Snippet

Optimizing Performance with @Cacheable Method Results

Spring's @Cacheable annotation stores the return value of a method in memory. Subsequent calls with the same productId return the cached value directly without re-executing the slow database logic, significantly optimizing application response times.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
@Service
public class ProductService {
@Cacheable(value = "products", key = "#productId")
public String findProductDetails(Long productId) {
simulateSlowDatabaseCall();
return "Product: " + productId;
}
private void simulateSlowDatabaseCall() {
try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}
spring
Breakdown
1
@Cacheable(value = "products", key = "#productId")
Instructs Spring to look up cached results in the 'products' cache using the 'productId' key before invoking the method.
2
return "Product: " + productId;
Returns the computed product string only when a cache miss occurs.