Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda