TL;DR
- Scenario: Using Guava Cache for local caching in Java projects, need to understand deletion strategy, expiration mechanism and common pitfalls
- Conclusion: Guava Cache uses ‘lazy cleanup + LRU+FIFO’ strategy. Passive deletion and active deletion need to be used together
- Output: Complete deletion strategy explanation + expiration mechanism details + error quick reference
Guava Cache Data Deletion Mechanism
1. Passive Deletion
Size-based Deletion: When cache element count reaches the preset maximum capacity, automatically remove the least recently used entry according to LRU algorithm.
Time-based Deletion:
expireAfterAccess: Entry automatically removed if not accessed within specified timeexpireAfterWrite: Entry automatically removed after creation or update exceeds specified time
Reference-based Deletion: When values are wrapped with WeakReference or SoftReference, they are automatically recycled by garbage collector when memory is insufficient.
2. Active Deletion
- Explicitly call
invalidatemethod to delete single key - Call
invalidateAllmethod for batch deletion - Listen for deletion events through
RemovalListener - Call
cleanUpmethod for active cleanup of expired entries
Important: Lazy Deletion Mechanism
Guava Cache uses lazy deletion mechanism. “After expiration time, cache.size() still hasn’t decreased” because access/maintenance logic hasn’t been triggered, or cleanUp hasn’t been called.
Solutions:
- Supplement
cache.cleanUp()in scheduled tasks or critical paths - Or trigger recycling through access
Error Quick Reference
| Symptom | Root Cause | Fix |
|---|---|---|
| size doesn’t decrease after expiration time | Lazy deletion not triggered | Call cleanUp() or trigger access |
| maximumSize reached but no eviction | LRU+FIFO strategy inconsistent with expectation | Print cache.asMap() for debugging |
| Memory usage continuously increases | No limit on maximumSize or expiration policy | Set reasonable parameters |
Application Scenario Examples
- E-commerce platform product cache: Use
expireAfterWriteto ensure price information updates regularly - User session management: Use
expireAfterAccessto automatically clean up long-inactive user sessions - Hot data cache: Use size-based deletion to prevent cache from occupying too much memory