Configure Caffeine Cache in Java with Eviction Policies
Set up Caffeine cache in a Java application with size-based, time-based, and weighted eviction policies for high-performance local caching.
Overview
Caffeine is a local caching library for the JVM that holds higher hit rates than the LRU-based caches most teams reach for first, thanks to a Window TinyLFU admission policy. It handles size-based, time-based, and weighted eviction, reference-based eviction (weak keys/values), refresh-ahead reloading, and synchronous or asynchronous loading.
This recipe covers a standalone Caffeine cache, each eviction policy with runnable code, Spring Boot’s @Cacheable integration, statistics for tuning, and a two-level L1/L2 setup with Redis. For caching at the HTTP layer instead, see HTTP Cache-Control Headers for APIs and Static Assets.
When to Use This
- Application-local caching where Redis or Memcached is overkill
- Read-heavy workloads with predictable access patterns
- Caching computed values, database lookups, or HTTP responses inside one JVM
- Spring Boot applications needing
@Cacheablebacked by a fast local cache
Skip Caffeine when several instances must share cache state (use Redis or Hazelcast), when entries must survive a restart (use a disk-backed store), or when you need strict coherence across nodes — a local cache can always serve a stale entry that another node already updated.
Prerequisites
- Java 17+
- Maven or Gradle
- Spring Boot 3+ (optional, for the Spring integration)
Solution
1. Add the Caffeine dependency
<!-- pom.xml -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
For Spring Boot integration, pull in the cache starter alongside Caffeine:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
2. Basic cache with size eviction
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
Cache<String, User> userCache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(30, TimeUnit.MINUTES)
.recordStats()
.build();
// Put
userCache.put("user:123", new User("123", "Alice"));
// Get (returns null if absent)
User user = userCache.getIfPresent("user:123");
// Get with loader (computes and caches if absent)
User loaded = userCache.get("user:456", key -> fetchUserFromDb("456"));
// Invalidate
userCache.invalidate("user:123");
userCache.invalidateAll();
3. Time-based eviction
// Entries expire 10 minutes after they were written
Cache<String, String> writeExpireCache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(5_000)
.build();
// Entries expire 5 minutes after they were last read
Cache<String, String> accessExpireCache = Caffeine.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.maximumSize(5_000)
.build();
// Both: expire 30 min after write, or after 10 min without reads
Cache<String, String> hybridCache = Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.expireAfterAccess(10, TimeUnit.MINUTES)
.build();
expireAfterAccess suits session-like data that should live while it’s actively used. One caveat: a key that gets read constantly never expires, so it can serve stale data forever. Pair it with expireAfterWrite as an upper bound when freshness matters.
4. Weighted eviction
When entries have different sizes (cached responses of varying length, deserialized objects of different depth), bound the cache by weight rather than count:
Cache<String, String> weightedCache = Caffeine.newBuilder()
.maximumWeight(10_000_000) // ~10MB budget
.weigher((String key, String value) -> value.length())
.build();
weightedCache.put("small", "hello"); // weight: 5
weightedCache.put("large", "x".repeat(100_000)); // weight: 100000
The weigher runs once at insertion. If a cached object’s size can change after you put it, weight-based eviction stops reflecting reality — either make entries immutable or re-put the entry after mutating it.
5. Loading cache (auto-populate)
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
LoadingCache<String, Product> productCache = Caffeine.newBuilder()
.maximumSize(5_000)
.expireAfterWrite(15, TimeUnit.MINUTES)
.refreshAfterWrite(10, TimeUnit.MINUTES) // reload in background before expiry
.build(key -> fetchProductFromDb(key));
// Automatically loads on miss
Product p1 = productCache.get("product:1");
Map<String, Product> batch = productCache.getAll(List.of("product:1", "product:2"));
6. Async loading cache
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
AsyncLoadingCache<String, User> asyncCache = Caffeine.newBuilder()
.maximumSize(10_000)
.buildAsync(key -> fetchUserAsync(key));
CompletableFuture<User> future = asyncCache.get("user:789");
User user = future.join();
The async variant shines when the loader does I/O: concurrent misses for the same key share one in-flight computation instead of stampeding the database.
7. Spring Boot integration
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CaffeineCacheManager cacheManager() {
CaffeineCacheManager manager = new CaffeineCacheManager();
manager.setCaffeine(Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(30, TimeUnit.MINUTES)
.recordStats());
return manager;
}
// Per-cache configuration
@Bean
public CacheManager multiCacheManager() {
CaffeineCacheManager manager = new CaffeineCacheManager("users", "products", "config");
manager.registerCustomCache("users", Caffeine.newBuilder()
.maximumSize(5_000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build());
manager.registerCustomCache("products", Caffeine.newBuilder()
.maximumSize(20_000)
.expireAfterWrite(30, TimeUnit.MINUTES)
.build());
return manager;
}
}
For pure annotation-driven caching without a custom manager, Spring Boot also accepts a spring.cache.caffeine.spec property (e.g. maximumSize=500,expireAfterWrite=600s) in application.properties. Once the manager is in place, the standard Spring annotations work:
@Service
public class UserService {
@Cacheable(value = "users", key = "#id")
public User getUser(String id) {
return userRepository.findById(id); // Only called on cache miss
}
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
return userRepository.save(user); // Updates cache
}
@CacheEvict(value = "users", key = "#id")
public void deleteUser(String id) {
userRepository.deleteById(id); // Removes from cache
}
@CacheEvict(value = "users", allEntries = true)
public void clearUserCache() {
// Clear entire cache
}
}
For the annotation model in depth, see Spring Cache Annotations in Java.
8. Cache statistics
Cache<String, User> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.recordStats()
.build();
// After some operations...
com.github.benmanes.caffeine.cache.stats.CacheStats stats = cache.stats();
System.out.println("Hit rate: " + stats.hitRate());
System.out.println("Hits: " + stats.hitCount());
System.out.println("Misses: " + stats.missCount());
System.out.println("Evictions: " + stats.evictionCount());
System.out.println("Average load time: " + stats.averageLoadPenalty() + " ns");
System.out.println("Cache size: " + cache.estimatedSize());
Two stats worth watching in production: evictionCount() climbing steadily means the cache is undersized, and averageLoadPenalty() tells you what each miss costs — if it approaches the latency of the uncached operation, the cache earns nothing.
How It Works
Choosing an eviction policy
| Policy | Builder method | Evicts when | Good for |
|---|---|---|---|
| Size | maximumSize(n) | Over n entries, least-frequent first | Bounded collections of similar items |
| Time (write) | expireAfterWrite(t) | Fixed TTL from insertion | Data with known staleness tolerance |
| Time (access) | expireAfterAccess(t) | TTL resets on each read | Session-like, actively-used data |
| Weight | maximumWeight(w) + weigher | Total weight exceeds w | Entries of variable size |
| References | weakKeys/weakValues/softValues | GC collects them | Memory-sensitive caches |
| Refresh | refreshAfterWrite(t) | Reloads in background after t | Hot keys where blocking is unacceptable |
Window TinyLFU admission
A plain LRU cache evicts whatever was used least recently. That fails on bursty or scanning workloads — one large scan flushes the whole cache even though every scanned entry is read exactly once. Caffeine instead tracks how often each key is accessed with a small frequency sketch (a Count-Min-style structure using 4-bit counters), then decides admission by frequency, not recency.
The cache is split into a small window region (about 1% of capacity) for new arrivals and a main region using segmented LRU. When space runs out, the eviction candidate’s frequency is compared against the victim’s; a cold candidate loses and never enters, which is how Caffeine resists pollution from one-off scans. Frequently accessed entries migrate into the protected segment of the main space and become hard to evict.
Eviction and expiry are lazy
Size eviction runs asynchronously in amortized batches, so writes don’t stall while the cache trims. Time-based expiry is also lazy: expired entries are reclaimed during reads and periodic maintenance, not by a dedicated timer thread. If you need prompt cleanup (sensitive data, tight memory), configure Scheduler.systemScheduler() as shown in the Variants section.
Variants
Reference-based eviction
Let the garbage collector reclaim entries when memory is tight:
Cache<String, User> cache = Caffeine.newBuilder()
.weakKeys() // Keys held weakly — evicted once the key is unreachable
.weakValues() // Values held weakly
.build();
Cache<String, User> softCache = Caffeine.newBuilder()
.softValues() // Values collected only under memory pressure
.build();
Use softValues for “nice to keep but disposable” data. Use weakKeys only when you control key identity — see Common Mistakes.
Scheduled cleanup
Force proactive cleanup instead of purely lazy expiry:
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.scheduler(Scheduler.systemScheduler()) // Enables periodic maintenance
.build();
Multi-level cache (L1 Caffeine + L2 Redis)
Caffeine in front of Redis gives you sub-microsecond hits for hot keys while Redis stays the shared source of truth across instances:
public class MultiLevelCache {
private final Cache<String, String> l1 = Caffeine.newBuilder()
.maximumSize(1_000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
private final RedisTemplate<String, String> l2;
public String get(String key) {
String l1Value = l1.getIfPresent(key);
if (l1Value != null) return l1Value;
String l2Value = l2.opsForValue().get(key);
if (l2Value != null) {
l1.put(key, l2Value); // Populate L1
return l2Value;
}
String dbValue = fetchFromDb(key);
l1.put(key, dbValue);
l2.opsForValue().set(key, dbValue, 30, TimeUnit.MINUTES);
return dbValue;
}
}
Keep the L1 TTL short (seconds to a few minutes): every L1 entry is potentially stale relative to Redis, and there’s no built-in invalidation channel between them. For the Redis side of this pattern in another language, see Redis Cache Decorator in Python or In-Memory LRU Cache in Node.js.
Best Practices
- Set
maximumSizefrom your heap budget: A cache that’s too large causes GC pressure; too small churns evictions. Start conservative, grow based onevictionCount. - Record stats from day one:
recordStats()is off by default and cheap. A hit rate below 50% means the cache is misconfigured or the workload isn’t cacheable. - Bound time and size:
expireAfterWritealone still lets the cache grow to its size limit; combining both protects against bursts of unique keys. - Use
refreshAfterWritefor hot keys: Reloads happen in the background while the old value keeps serving — no herd of threads blocking on the same miss. - Size
initialCapacitywhen you know it: Avoids rehashing during warmup on large caches. - Give each Spring cache its own config: Users, products, and config data have different sizes and lifetimes; one global spec fits none of them well.
Common Mistakes
- No size bound: Without
maximumSizeormaximumWeightthe cache grows until it pressures the heap. Always set one. weakKeyswithStringkeys:weakKeys()switches key comparison fromequals()to reference identity (==). Two equalStringinstances with different identity never match, so lookups miss constantly and entries vanish when the key object is collected. UseweakKeysonly for keys whose identity you control (canonical instances you hold elsewhere).- Expecting loader
nulls to be cached: Caffeine never stores null values. If your mapping function returnsnull,get()returnsnulland the loader runs again on every call — under concurrency that means repeated database hits for a key that doesn’t exist. ReturnOptional.empty()-style sentinels, a null-object value, or throw an exception instead. - Leaving stats off until you need them: You can’t retroactively enable
recordStats(); add it when you build the cache. - Oversizing for “just in case”: A 1M-entry cache of large deserialized objects can consume gigabytes and lengthen GC pauses. Profile real entry sizes first.
- Refreshing more often than the data changes:
refreshAfterWrite(1, MINUTES)against data updated hourly burns loader calls for nothing. Match refresh interval to the source’s change rate.
See Also
- Caffeine documentation and benchmarks (GitHub)
- Spring Boot caching reference
- TinyLFU: A Highly Efficient Cache Admission Policy — the paper behind Caffeine’s eviction algorithm
- Companion code: runnable versions of every example in this recipe live in the stack-practices-resources repository under
resources/recipes/caching/java-caffeine-cache-configuration/.
Frequently Asked Questions
Caffeine vs Guava Cache — which should I use?
Caffeine. It's the successor to Guava Cache, written by the same author, with better hit rates (TinyLFU vs LRU), higher concurrent throughput, and async loading support. Guava Cache remains in maintenance mode.
How does Caffeine compare to Redis?
They solve different problems. Caffeine is in-process: nanosecond-to-microsecond reads, no network, but confined to one JVM and lost on restart. Redis is shared infrastructure: network latency per call, but consistent across instances. The common production pattern is Caffeine as L1 in front of Redis as L2.
Can I use Caffeine for distributed caching?
No — it's strictly local to the JVM. For distributed caching, front Redis/Hazelcast with Caffeine as an L1 tier, or use a distributed cache directly.
What is the maximum cache size?
Whatever fits your heap. There's no library-imposed cap on maximumSize; the real limit is memory footprint and GC behavior. Caches that outgrow the heap belong in off-heap stores (Ehcache tiered, Chronicle Map) rather than in Caffeine.
What's the difference between refreshAfterWrite and expireAfterWrite?
expireAfterWrite removes the entry at the TTL; the next reader blocks while the value reloads. refreshAfterWrite keeps serving the old value and reloads in the background once the entry is older than the refresh interval. Refresh is for hot keys where a blocking reload is unacceptable; expiry is for data that must not be served past its TTL.
Related Resources
Cache Function Results with Redis and TTL in Python
Build a Python decorator that caches function return values in Redis with configurable TTL, key generation, and cache invalidation
RecipeImplement an LRU Cache in Node.js
Build a least-recently-used cache in Node.js with O(1) get and set using a Map plus a doubly linked list, or a Map-only version for small caches.
RecipeUse Spring Cache Annotations with Redis Backend
Apply Spring's @Cacheable, @CachePut, and @CacheEvict annotations with a Redis cache manager for declarative caching in Java applications.
GuideComplete Guide to Redis Caching Strategies
Choose and implement the right Redis caching pattern — cache-aside to refresh-ahead — with eviction, TTL, and production ops guidance.
RecipeHTTP Cache-Control Headers for APIs and Static Assets
Set Cache-Control, ETag, and Last-Modified headers to control browser and CDN caching for API responses and static assets