idwx
idwx

Reputation: 57

How to update Java ConcurrentHashMap in Scala

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!

Upvotes: 0

Views: 188

Answers (1)

idwx
idwx

Reputation: 57

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)

Upvotes: 1

Related Questions