Cache

class Cache<K, V>(source)

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")

With TTL and LRU eviction:

val cache = Cache.create<String, User>(config = CacheConfig(
maxSize = 1000,
ttl = 5.minutes,
evictionStrategy = EvictionStrategy.LRU
))

Compute-if-absent:

val user = cache.getOrPut("user-1") {
userRepository.findById("user-1")
}

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 miss

DSL builder:

val cache = cache<String, User> {
maxSize = 500
ttl = 10.minutes
evictionStrategy = EvictionStrategy.LFU
}

Parameters

config

Configuration for cache behavior

Type Parameters

K

Key type

V

Value type

Types

Link copied to clipboard
object Companion

Factory for Cache.

Functions

Link copied to clipboard
fun addListener(listener: CacheListener<K, V>)

Adds a listener for cache events.

Link copied to clipboard
suspend fun cleanUp(): Int

Removes all expired entries from the cache.

Link copied to clipboard
suspend fun clear()

Removes all entries from the cache.

Link copied to clipboard
suspend fun containsKey(key: K): Boolean

Checks if the cache contains a non-expired entry for the given key.

Link copied to clipboard
suspend fun get(key: K): V?

Gets a value from the cache by key.

Link copied to clipboard
suspend fun getOrPut(key: K, loader: suspend () -> V): V

Gets a cached value or computes and caches it if absent.

Link copied to clipboard
suspend fun invalidate(key: K)

Invalidates a cache entry by key.

Link copied to clipboard
suspend fun invalidateAll(keys: Iterable<K>)

Invalidates multiple cache entries.

Link copied to clipboard
suspend fun keys(): Set<K>

Returns all non-expired keys in the cache.

Link copied to clipboard
suspend fun put(key: K, value: V)

Puts a value into the cache, evicting an entry if at capacity.

Link copied to clipboard
suspend fun remove(key: K): V?

Removes an entry from the cache.

Link copied to clipboard
fun removeListener(listener: CacheListener<K, V>)

Removes a previously added cache listener.

Link copied to clipboard
suspend fun resetStatistics()

Resets all statistics counters to zero.

Link copied to clipboard
suspend fun size(): Int

Returns the total number of entries in the cache (including expired).

Link copied to clipboard

Returns a snapshot of the current cache statistics.

Link copied to clipboard
suspend fun validKeys(): Set<K>

Returns all non-expired keys in the cache. Alias for keys.

Link copied to clipboard
suspend fun validSize(): Int

Returns the number of non-expired entries in the cache.