I am using Kotlin and I have a mutableMap with Key as String, when I have 2 threads trying to access and put with same key, some weird things happen that my log shows the map size is 2 (not 1), I also log the key and value there but there is only one entry...
@Component
class CacheImpl {
protected val cache: MutableMap<String, String> = HashMap() //same behavior with ConcurrentHashMap
fun fetchFromCache(key: String) {
log.info("cache size: ${cache.size}")
log.info("cache keys: ${cache.keys}")
log.info("cache keys count: ${cache.keys.count()}")
cache.computeIfAbsent(id) {
key -> fetchFromClient(key)
}
}
}
fun serviceCall() {
// should fetch from client
val result1 = cache.fetchFromCache("123")
// should fetch from service
val result2 = cache.fetchFromCache("123")
}
So I have 2 threads calling the serviceCall at same time, in log I found
[thread: 2] - cache size: 0
[thread: 4] - cache size: 0
[thread: 2] - cache keys: []
[thread: 4] - cache keys: []
[thread: 2] - cache keys count: 2
[thread: 4] - cache keys count: 2
[thread: 2] - cache size: 2
[thread: 2] - cache keys count: 2
[thread: 2] - cache keys: [123]
[thread: 4] - cache size: 2
[thread: 4] - cache keys count: 2
[thread: 4] - cache keys: [123]
I also tried with LinkedHashMap and it's even more weird, in LinkedHashMap you can see my map contains two exact same key!
[thread: 2] - cache size: 0
[thread: 4] - cache size: 0
[thread: 2] - cache keys: []
[thread: 4] - cache keys: []
[thread: 2] - cache keys count: 2
[thread: 4] - cache keys count: 2
[thread: 2] - cache size: 2
[thread: 2] - cache keys count: 2
[thread: 2] - cache keys: [123,123]
[thread: 4] - cache size: 2
[thread: 4] - cache keys count: 2
[thread: 4] - cache keys: [123,123]
- shouldn't Map only maintain a unique key always?
- Why my map size is not matching with key count?