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]
The HashMap is not thread-safe, so when you put in two threads, it happened the weird scene. I suggest you use the ConcurrentWeakMap. as the doc says
This is a very limited implementation, not suitable as a generic map replacement. // It has lock-free get and put with synchronized rehash for simplicity (and better CPU usage on contention)
But it only makes sure the map operation is thread-safe, you have to make the method thread-safe.
@Synchronized
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)
}
}
At the same time, the key you use generates from fetchFromClient, every time it returns a new object. it is also the reason. you should use the putIfAbseent, if you want override the value which has exits