Cache
Thread-safe cache with TTL, eviction strategies, and statistics.
Provides a configurable in-memory cache with support for multiple eviction strategies (LRU, LFU, FIFO), time-to-live expiration, and hit/miss statistics.
Basic usage:
val cache = Cache.create<String, User>()
cache.put("user-1", User("Alice"))
val user = cache.get("user-1") // User("Alice")Content copied to clipboard
With TTL and LRU eviction:
val cache = Cache.create<String, User>(config = CacheConfig(
maxSize = 1000,
ttl = 5.minutes,
evictionStrategy = EvictionStrategy.LRU
))Content copied to clipboard
Compute-if-absent:
val user = cache.getOrPut("user-1") {
userRepository.findById("user-1")
}Content copied to clipboard
Auto-loading cache:
val cache = LoadingCache.create<String, User>(
config = CacheConfig(maxSize = 100)
) { key ->
userRepository.findById(key)
}
val user = cache.get("user-1") // auto-loads on missContent copied to clipboard
DSL builder:
val cache = cache<String, User> {
maxSize = 500
ttl = 10.minutes
evictionStrategy = EvictionStrategy.LFU
}Content copied to clipboard
Parameters
config
Configuration for cache behavior
Type Parameters
K
Key type
V
Value type
Functions
Link copied to clipboard
Adds a listener for cache events.
Link copied to clipboard
Checks if the cache contains a non-expired entry for the given key.
Link copied to clipboard
Invalidates a cache entry by key.
Link copied to clipboard
Invalidates multiple cache entries.
Link copied to clipboard
Removes a previously added cache listener.
Link copied to clipboard
Resets all statistics counters to zero.
Link copied to clipboard
Returns a snapshot of the current cache statistics.