Lightweight coroutine-aware in-memory cache with TTL and LRU eviction
implementation com.philiprehberger:cache-kitLightweight coroutine-aware in-memory cache with TTL and LRU eviction.
implementation("com.philiprehberger:cache-kit:0.2.0")
<dependency>
<groupId>com.philiprehberger</groupId>
<artifactId>cache-kit</artifactId>
<version>0.2.0</version>
</dependency>
import com.philiprehberger.cachekit.*
import kotlin.time.Duration.Companion.minutes
val userCache = cache<String, User> {
maxSize = 1000
expireAfterWrite = 5.minutes
onEvict = { key, _ -> println("Evicted user $key") }
}
// Basic get/put
userCache.put("user-1", loadUser("user-1"))
val user = userCache.get("user-1")
// Concurrent calls for the same key only trigger one load
val user = userCache.getOrLoad("user-1") { key ->
fetchUserFromDatabase(key)
}
val sessionCache = cache<String, Session> {
expireAfterAccess = 30.minutes // Extends lifetime on each read
}
val stats = userCache.stats()
println("Hit rate: ${stats.hitRate}")
println("Hits: ${stats.hits}, Misses: ${stats.misses}")
println("Evictions: ${stats.evictions}, Size: ${stats.size}")
// Only store if not already cached
val existing = cache.putIfAbsent("user-1", newUser)
if (existing != null) {
println("Already cached: $existing")
}
val users = cache.getAll(listOf("user-1", "user-2", "user-3"))
// Returns a map of found entries only
// Remove all entries matching a condition
val removed = cache.invalidateIf { key, _ -> key.startsWith("temp_") }
println("Removed $removed entries")
| Class / Function | Description |
|---|---|
cache { } | DSL builder for creating cache instances |
Cache<K, V> | Main cache class with get, put, getOrLoad, invalidate, clear, stats |
CacheConfig<K, V> | Configuration: maxSize, expireAfterWrite, expireAfterAccess, onEvict |
CacheStats | Data class with hits, misses, evictions, size, and hitRate |
Cache.putIfAbsent(key, value) | Store only if key is not already cached |
Cache.getAll(keys) | Batch get returning map of found entries |
Cache.invalidateIf { } | Remove entries matching a predicate |
Cache.size() | Get current number of cached entries |
./gradlew test # Run tests
./gradlew check # Run all checks
./gradlew build # Build JAR
If you find this project useful: