Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
MutableMap modified by multiple threads and map.size not equal to key count

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?
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda