If you run this code
runBlocking {
launch { cache.get(0) { fetchUser() } }
launch { cache.get(0) { fetchUser() } }
launch { cache.get(0) { fetchUser() } }
launch { cache.get(0) { fetchUser() } }
}
suspend fun fetchUser(): Int {
delay(100)
println("Hitting the network to fetch user!")
return 0
}
then the message "Hitting the network to fetch user!" is printed 4 times.
I would expect this cache to be synchronised by key in a way that when multiple threads are trying to read a value from a key in which the value is suspend then it will await till the value is computed and then deliver it, rather than calling it once per thread and then race to see who writes to the cache first.
If you run this code
then the message "Hitting the network to fetch user!" is printed 4 times.
I would expect this cache to be synchronised by key in a way that when multiple threads are trying to read a value from a key in which the value is suspend then it will await till the value is computed and then deliver it, rather than calling it once per thread and then race to see who writes to the cache first.