Using Caffeine Cache in Spring Boot: Features, Algorithms, and Configuration

This article explains the Caffeine local cache library, its W‑TinyLFU eviction algorithm, how it improves on Guava Cache, and provides detailed examples of manual, synchronous, and asynchronous loading, eviction policies, reference types, statistics, and Spring Boot integration with code snippets.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Using Caffeine Cache in Spring Boot: Features, Algorithms, and Configuration

Caffeine Cache is a modern Java caching library that builds on Guava Cache's ideas but uses the advanced W‑TinyLFU algorithm to achieve near‑optimal hit rates while supporting thread‑safe operations, expiration, and eviction policies.

The library offers three loading strategies:

Manual loading using

Cache<String, Object> cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.SECONDS).maximumSize(10).build(); Object value = cache.get(key, k -> setValue(k));

Synchronous loading with a CacheLoader implementation:

LoadingCache<String, Object> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(k -> setValue(k));

Asynchronous loading via AsyncLoadingCache and CompletableFuture:

AsyncLoadingCache<String, Object> cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).buildAsync(k -> setAsyncValue(k).get());

Caffeine provides three eviction policies: size‑based ( .maximumSize() or .maximumWeight()), time‑based ( .expireAfterAccess(), .expireAfterWrite(), or a custom Expiry), and reference‑based (weak or soft keys/values). Weak and soft references cannot be mixed with AsyncLoadingCache, and CacheWriter cannot be used with weak keys.

The W‑TinyLFU algorithm combines LFU’s frequency tracking (using a Count‑Min Sketch with sliding‑window decay) and LRU’s recency handling to handle both steady and bursty access patterns efficiently.

Spring Boot 2.x replaces Guava with Caffeine as the default local cache. To use it, add the dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.6.2</version>
</dependency>

Enable caching with @EnableCaching and configure caches via properties (e.g.,

spring.cache.caffeine.spec=initialCapacity=50,maximumSize=500,expireAfterWrite=10s

) or Java configuration beans that create CaffeineCache instances, set TTL, maximum size, and record statistics.

Cache operations can be performed with Spring annotations: @Cacheable(value="userCache", key="#id", sync=true) – reads from cache or loads and stores the result. @CachePut(value="userCache", key="#user.id") – always executes the method and updates the cache. @CacheEvict(value="userCache", key="#user.id") – removes the entry.

Additional features include removal listeners (

.removalListener((k, v, cause) -> System.out.printf("Key %s was removed (%s)%n", k, cause))

), cache writers for persisting entries, and statistics via .recordStats() (hit rate, eviction count, load penalty).

Overall, Caffeine provides a flexible, high‑performance caching solution for Java backend applications, especially when integrated with Spring Boot’s caching abstraction.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaCacheCaffeineSpringBoot
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.