Caching
suggest changeA cache keeps the result of an expensive operation (a database query, an HTTP call, a slow computation) so the next request for the same thing can be answered from memory.
Caching is easy to start and hard to get right. Every cache has to answer the same questions:
- key: what identifies a cached value? Keys need correct
equalsandhashCode, which is whydata classkeys work well. - size: how many entries are allowed before old ones are evicted?
- freshness: how long is a value valid (time to live, TTL)?
- concurrency: what happens when many threads or coroutines ask for the same missing key at the same time?
This article goes from the simplest option to the most capable:
- memoization with
getOrPut by lazyfor a single value- thread-safe caches with
ConcurrentHashMap - an LRU cache built on
LinkedHashMap - a TTL cache with
kotlin.time - caching
suspendfunctions without duplicate loads - production caching with the Caffeine library
Memoization with getOrPut
The simplest cache is a HashMap plus getOrPut. getOrPut returns the existing value, or computes, stores and returns a new one:
val cache = HashMap<Int, Long>()
fun slowSquare(n: Int): Long {
println("computing $n")
Thread.sleep(100) // pretend this is expensive
return n.toLong() * n
}
fun cachedSquare(n: Int): Long = cache.getOrPut(n) { slowSquare(n) }
fun main() {
println(cachedSquare(4))
println(cachedSquare(4))
println(cachedSquare(5))
}
computing 4
16
16
computing 5
25
Memoization turns exponential recursive algorithms into linear ones. Naive Fibonacci makes about 2^n calls; with a cache each value is computed once:
import java.math.BigInteger
val memo = HashMap<Int, BigInteger>()
fun fib(n: Int): BigInteger =
if (n < 2) n.toBigInteger()
else memo.getOrPut(n) { fib(n - 1) + fib(n - 2) }
fun main() {
println(fib(100))
}
354224848179261915075
This works because Kotlin's getOrPut is a plain "get, compute, put" sequence, so the lambda can freely add other keys to the map. Don't do the same with ConcurrentHashMap.computeIfAbsent: modifying the map from inside its own mapping function throws IllegalStateException: Recursive update.
A generic memoize function
You can wrap any single-argument function in a cache:
fun <A, R> memoize(f: (A) -> R): (A) -> R {
val cache = HashMap<A, R>()
return { a -> cache.getOrPut(a) { f(a) } }
}
fun main() {
val slowLength = { s: String ->
println("computing '$s'")
s.length
}
val fastLength = memoize(slowLength)
println(fastLength("kotlin"))
println(fastLength("kotlin"))
println(fastLength("java"))
}
computing 'kotlin'
6
6
computing 'java'
4
For functions with several arguments, combine them into one key: a Pair, a Triple or, better, a data class:
data class PriceKey(val productId: Int, val currency: String)
val prices = HashMap<PriceKey, Double>()
fun price(productId: Int, currency: String): Double =
prices.getOrPut(PriceKey(productId, currency)) {
println("fetching price $productId $currency")
19.99
}
Two caveats about getOrPut:
- it is not thread-safe on a
HashMap; use it only from one thread, or seeConcurrentHashMapbelow - it treats a stored
nullas "missing", so if the computed value can benullthe computation runs every time. Wrap nullable results (for example inOptionalor your ownsealedtype) if "not found" must be cached too.
A single value: by lazy
When there is just one value to cache, such as a parsed configuration file or a compiled regex, use a lazy property:
class Config(private val path: String) {
val settings: Map<String, String> by lazy {
println("reading $path")
mapOf("port" to "8080", "host" to "localhost")
}
}
fun main() {
val config = Config("app.conf")
println("created")
println(config.settings["port"])
println(config.settings["host"])
}
created
reading app.conf
8080
localhost
By default lazy is synchronized: if several threads read the property at once, the initializer runs only once. You can choose a different mode:
lazy(LazyThreadSafetyMode.SYNCHRONIZED): the default, initializer runs exactly oncelazy(LazyThreadSafetyMode.PUBLICATION): the initializer may run more than once concurrently, the first result winslazy(LazyThreadSafetyMode.NONE): no synchronization, fastest, only for single-threaded use (e.g. Android UI code)
A lazy value never expires. For values that must be refreshed, use one of the caches below.
Thread-safe caching with ConcurrentHashMap
In a server, many threads access the cache at once. ConcurrentHashMap.computeIfAbsent atomically computes a missing value, and the mapping function runs at most once per key:
import java.util.concurrent.ConcurrentHashMap
import kotlin.concurrent.thread
val cache = ConcurrentHashMap<String, Int>()
fun lookup(key: String): Int = cache.computeIfAbsent(key) { k ->
println("loading $k")
Thread.sleep(100)
k.length
}
fun main() {
val threads = List(4) { thread { lookup("hello") } }
threads.forEach { it.join() }
println(cache)
}
loading hello
{hello=5}
Four threads asked for the same key, but loading hello is printed only once: the other threads waited for the first one to finish.
Things to keep in mind:
- Kotlin's
getOrPuton aConcurrentMapis atomic in the sense that only one value is stored, but the lambda may run several times under contention. PrefercomputeIfAbsentwhen loading is expensive or has side effects. - While
computeIfAbsentruns, other updates to the same part of the map are blocked. Keep the mapping function reasonably short and never modify the map from inside it. ConcurrentHashMapdoes not allownullkeys or values. If the function returnsnull, nothing is stored.- The map grows forever. A cache without a size limit is a memory leak waiting to happen.
An LRU cache with LinkedHashMap
A least-recently-used (LRU) cache has a maximum size and, when full, evicts the entry that hasn't been used for the longest time.
java.util.LinkedHashMap has this built in. Created with accessOrder = true it keeps entries ordered from least to most recently accessed, and it calls removeEldestEntry after every insertion:
class LruCache<K, V>(private val maxSize: Int) {
private val map = object : LinkedHashMap<K, V>(16, 0.75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<K, V>?): Boolean =
size > maxSize
}
@Synchronized
operator fun get(key: K): V? = map[key]
@Synchronized
operator fun set(key: K, value: V) {
map[key] = value
}
@Synchronized
fun getOrPut(key: K, compute: () -> V): V = map.getOrPut(key, compute)
val size: Int
@Synchronized get() = map.size
@Synchronized
override fun toString(): String = map.toString()
}
fun main() {
val cache = LruCache<String, Int>(maxSize = 3)
cache["a"] = 1
cache["b"] = 2
cache["c"] = 3
println(cache)
cache["a"] // reading "a" makes it the most recently used
cache["d"] = 4 // cache is full: evicts "b", the least recently used
println(cache)
println(cache["b"])
}
{a=1, b=2, c=3}
{c=3, a=1, d=4}
null
Note that with accessOrder = true even a read modifies the map (it moves the entry to the end), so every access must be synchronized, not just writes. Here @Synchronized locks on the LruCache instance. Holding a lock while getOrPut computes a value blocks all other callers, which is fine for cheap computations but not for slow I/O.
Expiring entries with a TTL
Data from a database or a remote service goes stale. A time-to-live (TTL) cache stores, with each value, the moment it expires.
Measure time with kotlin.time.TimeSource rather than System.currentTimeMillis(). The monotonic time source isn't affected by wall-clock changes, and taking TimeSource as a parameter lets tests control time with TestTimeSource:
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TestTimeSource
import kotlin.time.TimeMark
import kotlin.time.TimeSource
class TtlCache<K, V>(
private val ttl: Duration,
private val timeSource: TimeSource = TimeSource.Monotonic,
) {
private class Entry<V>(val value: V, val expiresAt: TimeMark)
private val map = HashMap<K, Entry<V>>()
@Synchronized
fun get(key: K): V? {
val entry = map[key] ?: return null
if (entry.expiresAt.hasPassedNow()) {
map.remove(key)
return null
}
return entry.value
}
@Synchronized
fun put(key: K, value: V) {
map[key] = Entry(value, timeSource.markNow() + ttl)
}
@Synchronized
fun getOrPut(key: K, compute: () -> V): V =
get(key) ?: compute().also { put(key, it) }
}
fun main() {
val time = TestTimeSource()
val cache = TtlCache<String, String>(ttl = 10.seconds, timeSource = time)
cache.put("token", "abc123")
println(cache.get("token"))
time += 9.seconds
println(cache.get("token"))
time += 2.seconds
println(cache.get("token"))
}
abc123
abc123
null
In production code you would create it with the default time source: TtlCache<String, String>(5.minutes).
This cache removes an expired entry only when someone reads it. Keys that are never read again stay in memory, so a real implementation also needs a size limit or a periodic cleanup. At this point it's usually better to use a library such as Caffeine, shown below.
Caching suspend functions
With coroutines you can't call a suspend function from inside computeIfAbsent or getOrPut on a shared map. You also want to avoid a cache stampede: if 100 coroutines ask for the same missing key at once, the backend should be called once, not 100 times.
The trick is to cache the Deferred (the in-progress computation) instead of the value. Everyone who asks for the key awaits the same Deferred:
import kotlinx.coroutines.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
class SuspendCache<K : Any, V>(
private val scope: CoroutineScope,
private val loader: suspend (K) -> V,
) {
private val map = ConcurrentHashMap<K, Deferred<V>>()
suspend fun get(key: K): V {
val deferred = map.computeIfAbsent(key) { k ->
scope.async(start = CoroutineStart.LAZY) { loader(k) }
}
try {
return deferred.await()
} catch (e: Throwable) {
// the load itself failed or was cancelled: forget it so the next call retries
if (deferred.isCompleted) map.remove(key, deferred)
throw e
}
}
fun invalidate(key: K) {
map.remove(key)?.cancel()
}
}
fun main() = runBlocking {
val cacheScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val calls = AtomicInteger()
val users = SuspendCache<Int, String>(cacheScope) { id ->
calls.incrementAndGet()
delay(100) // simulate a network call
"user-$id"
}
val results = List(10) { async { users.get(42) } }.awaitAll()
println(results.distinct())
println("loader calls: ${calls.get()}")
println(users.get(42))
println("loader calls: ${calls.get()}")
cacheScope.cancel()
}
[user-42]
loader calls: 1
user-42
loader calls: 1
Design notes:
- The load runs in the cache's own
scope, not in the caller's. If one caller is cancelled (see Cancellation and timeouts) the load keeps going for the other callers;deferred.isCompletedis stillfalse, so the entry is kept. - The scope uses
SupervisorJob, so one failed load doesn't cancel the scope and every other load in it. CoroutineStart.LAZYmeans the coroutine starts on the firstawait(), aftercomputeIfAbsenthas returned, so no work runs while the map is locked.- A failed load is removed from the map, so errors are not cached.
- Like
ConcurrentHashMapabove, this cache has no size limit or expiry. You can get both by storing theDeferredvalues in a CaffeineCache<K, Deferred<V>>instead of aConcurrentHashMap.
Production caching with Caffeine
Caffeine is the standard in-memory cache for the JVM. It is used by Spring, and it gives you everything the hand-written caches above lack: size limits with a near-optimal eviction policy (W-TinyLFU), expiry, refresh, statistics and high concurrency.
// build.gradle.kts
dependencies {
implementation("com.github.ben-manes.caffeine:caffeine:3.3.1")
}
Manual cache
import com.github.benmanes.caffeine.cache.Caffeine
import java.time.Duration
data class User(val id: Int, val name: String)
fun loadUser(id: Int): User {
println("loading user $id")
return User(id, "user$id")
}
fun main() {
val cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(5))
.recordStats()
.build<Int, User>()
println(cache.get(1) { id -> loadUser(id) }) // miss: loads
println(cache.get(1) { id -> loadUser(id) }) // hit
println(cache.getIfPresent(2)) // miss: null, nothing loaded
cache.put(2, User(2, "bob"))
println(cache.getIfPresent(2)) // hit
cache.invalidate(2)
println(cache.getIfPresent(2)) // miss
val stats = cache.stats()
println("hits=${stats.hitCount()} misses=${stats.missCount()} hitRate=${stats.hitRate()}")
}
loading user 1
User(id=1, name=user1)
User(id=1, name=user1)
null
User(id=2, name=bob)
null
hits=2 misses=3 hitRate=0.4
cache.get(key) { ... } is atomic, like computeIfAbsent: concurrent callers for the same key wait for a single load. Use recordStats() and watch the hit rate in production; a cache with a low hit rate only costs memory.
Loading cache
If values are always loaded the same way, pass the loader to build and get a LoadingCache:
import com.github.benmanes.caffeine.cache.Caffeine
import java.time.Duration
data class User(val id: Int, val name: String)
fun loadUser(id: Int): User {
println("loading user $id")
return User(id, "user$id")
}
fun main() {
val users = Caffeine.newBuilder()
.maximumSize(1_000)
.expireAfterWrite(Duration.ofMinutes(10))
.refreshAfterWrite(Duration.ofMinutes(1))
.build<Int, User> { id -> loadUser(id) }
println(users.get(7))
println(users.get(7))
println(users.getAll(listOf(7, 8)))
}
loading user 7
User(id=7, name=user7)
User(id=7, name=user7)
loading user 8
{7=User(id=7, name=user7), 8=User(id=8, name=user8)}
expireAfterWrite and refreshAfterWrite work together: after 1 minute, the next read still returns the old value immediately while Caffeine reloads it in the background; after 10 minutes without a successful reload the entry is dropped. This keeps latency low and avoids many requests waiting on a reload at the same moment.
Eviction options
Caffeine's builder has options for most needs:
maximumSize(n): limit the number of entriesmaximumWeight(w)withweigher { key, value -> ... }: limit by an estimate of memory, e.g. bytes of a cached string or imageexpireAfterWrite(d): drop entries a fixed time after they were created or replacedexpireAfterAccess(d): drop entries not read or written for a while (session-like data)softValues(): let the garbage collector reclaim values under memory pressure (see Memory and garbage collection); usually a size limit is more predictableremovalListener { key, value, cause -> ... }: get notified when an entry is evicted, expired or invalidated
Eviction happens asynchronously, so right after a burst of writes the cache may briefly hold more than maximumSize entries. In tests, run maintenance on the calling thread and call cleanUp() to get deterministic results:
import com.github.benmanes.caffeine.cache.Caffeine
fun main() {
val cache = Caffeine.newBuilder()
.maximumSize(100)
.executor(Runnable::run) // run maintenance on the caller's thread
.build<Int, Int>()
for (i in 1..1_000) cache.put(i, i * i)
cache.cleanUp()
println(cache.estimatedSize())
}
100
Don't write tests that expect a specific key to be evicted: W-TinyLFU considers how often keys are used, not only how recently, so it doesn't behave like a strict LRU.
Pitfalls and best practices
- Always bound the cache. An unbounded
HashMapcache is the most common source of slow memory leaks. Set a size limit, a TTL, or both. - Cache immutable values. If a caller modifies a cached object (e.g. a
MutableList), every other caller sees the change. Store read-only types anddata classes withvalproperties. - Use good keys. Keys must have stable
equals/hashCode. Never use a mutable object as a key and never mutate a key after inserting it. Arrays use identity equality, soIntArraykeys don't work; convert them to aListfirst. - Decide whether to cache "not found" and errors. Caching a missing user avoids hitting the database for repeated bad requests, but it should have a shorter TTL. Errors usually shouldn't be cached at all.
- Invalidate on writes. When your code updates the underlying data, call
invalidate(key)so readers don't see the old value until it expires. - Remember that in-memory caches are per process. With several server instances each has its own copy, so invalidation on one instance doesn't affect the others. Use short TTLs, or a shared cache like Redis if all instances must agree.
- Measure. Check the hit rate and the latency you actually save. Caching something that is cheap to compute, or rarely requested twice, only adds complexity.
For caching HTTP responses in browsers and proxies, see the Cache-Control and ETag headers in HTTP headers.