0

I am puzzled by the behavior of ConcurrentHashMap. I have a map indexed by Long with Array as value. I tried using both putIfAbsent and computeIfAbsent to populate the map. The Scala worksheet/console does imply that the map has been updated, but get() always returns null. See below

val foo = new ConcurrentHashMap[Long, ConcurrentLinkedQueue[Int]]()

// val initialize = new ConcurrentLinkedQueue[Int]()
// initialize.add(1)
// initialize 

// foo.putIfAbsent(1, initialize)
foo.computeIfAbsent(1, k => new ConcurrentLinkedQueue[Int]()).add(2);

// When I inspect the content of foo, it does show {1=[2]}
foo 

// But get(1) still returns null! 
foo.get(1)

Any suggestion for why this is the case? How do I update the content of a concurrent hash map then? I am testing without explicit multithreaded access. The version of Scala is 2.12.8.

Many thanks!

1
  • I would assume you would need to use immutable data structure in scala in first place and maybe use actors patterns in case you would like to isolate thing to get "single threads illusion" etc
    – Pavel
    Commented Sep 15, 2022 at 9:43

1 Answer 1

1

I figured it out. In this case, the key 1 in the get method has type "Int". Casting it to Long solved the issue.

foo.get(1.toLong)

Not the answer you're looking for? Browse other questions tagged or ask your own question.