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 time
  • expireAfterWrite: 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 invalidate method to delete single key
  • Call invalidateAll method for batch deletion
  • Listen for deletion events through RemovalListener
  • Call cleanUp method 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

SymptomRoot CauseFix
size doesn’t decrease after expiration timeLazy deletion not triggeredCall cleanUp() or trigger access
maximumSize reached but no evictionLRU+FIFO strategy inconsistent with expectationPrint cache.asMap() for debugging
Memory usage continuously increasesNo limit on maximumSize or expiration policySet reasonable parameters

Application Scenario Examples

  • E-commerce platform product cache: Use expireAfterWrite to ensure price information updates regularly
  • User session management: Use expireAfterAccess to automatically clean up long-inactive user sessions
  • Hot data cache: Use size-based deletion to prevent cache from occupying too much memory