Hey! should this code work and be thread-safe and ...
# announcements
l
Hey! should this code work and be thread-safe and deadlock-free? I have a feeling it's causing a deadlock, but i cannot see how it could
Copy code
class SingleSlotCache<K, V> {
    @Volatile
    private var cacheData: Pair<K, V>? = null

    @Synchronized
    fun getValueBy(key: K, f: () -> V): V = cacheData
        ?.takeIf { (cachedKey, _) -> cachedKey == key }?.second
        ?: f().also { cacheData = Pair(key, it) }
}
as the whole function is synchronized, if one thread is currently accessing the value (and maybe calculating and writing it, because the key doesn't match) the next one to access it should have to wait, and then afterwards just use the value from the first thread (as long as the keys match), shouldn't they? Or am I missing something obvious in how
@Synchronized
works or something...