Java time-based map/cache with expiring keys
Implement a self-expiring map in Java using Guava's Cache
that evicts entries after a predetermined time. This is achieved using CacheBuilder
for automatic key expiration:
This neat piece of code sets up a map where entries expire 10 minutes post-insertion. Make sure to include Guava in your project build to access CacheBuilder
.
Exploring alternative solutions
If Guava doesn't strike a chord with you, fret not. There are other solutions to implement a time-based cache plus a few trade-offs to consider.
CompletableFuture for cleanup
CompletableFuture
can help schedule cleanup tasks. It isn't a full cache solution, but can certainly find a place in simple contexts:
This approach schedules a CompletableFuture
to remove the key from the map after a delay. It's resource-light but doesn’t bode well with scale.
Scheduled thread pool for map cleaning
For greater control, employ a ScheduledExecutorService
to periodically purge expired entries:
This approach ensures that a cleanup runs predictably to clear expired items, especially useful when expiration logic isn't the simplest.
Other caching options
Apart from Guava, there's an entire repertoire of cache implementations to fit your use case. Let's take a quick look:
WeakConcurrentHashMap on GitHub
Perfect for memory-conscious work, it cleans up after entries are no longer in use:
PassiveExpiringMap from Apache Commons
It's a simple, lightweight solution, but beware - it doesn't play well in concurrent scenarios without additional synchronization:
Ehcache
A power-packed solution with advanced features for enterprise setups. Plus, it supports programmatic configuration:
Evaluate factors such as performance, concurrency, memory consumption, and maintenance complexity when choosing your caching solution.
Was this article helpful?