Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -164,14 +164,15 @@ public class InMemoryKache<K : Any, V : Any> internal constructor(
override suspend fun getOrPut(key: K, creationFunction: suspend (key: K) -> V?): V? {
get(key)?.let { return it }

creationMutex.withLock {
val deferred = creationMutex.withLock {
if (creationMap[key] == null && map[key] == null) {
@Suppress("DeferredResultUnused")
internalPutAsync(key, creationFunction)
} else {
creationMap[key]
}
}

return get(key)
return deferred?.let { getFromCreation(key, it) } ?: get(key)
}

override suspend fun put(key: K, creationFunction: suspend (key: K) -> V?): V? =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -686,4 +686,20 @@ class InMemoryKacheTest {

assertEquals(0, kache.size)
}

@Test
fun getOrPutHighConcurrency() = runTest {
// Regression test for https://github.com/MayakaApps/Kache/issues/239
// With more keys than maxSize, LRU eviction kicks in. In old code, a creation deferred
// could complete (on Dispatchers.Default) and get evicted between the creationMutex.withLock
// exit and the trailing get(key) call, returning null.
// Uses the real default creationScope (Dispatchers.Default) — testInMemoryKache overrides
// it to the single-threaded test dispatcher, which hides the race.
val kache = InMemoryKache<String, String>(maxSize = 100)

(0..20_000).forEach {
launch { assertNotNull(kache.getOrPut(it.toString()) { it.toString() }) }
}
}

}