Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between scala TrieMap and Java ConcurrentHashMap

Tags:

scala

It says that scala TrieMap will produce a consistent iterator when iterating over the TrieMap, I don't understand what consistent here really means.

I need an collection to build an object pools, that is, objects in the pool will be borrowed/released concurrently, and in the meanwhile, a scheduled thread will iterate over this collection,and check whether there are stale objects, if there is, then create a new one and delete the stale one from the collection.

I am evaluating whether scala TrieMap can be used as the pool.

Also, can someone show some code to illustrate the difference between scala TrieMap and Java ConcurrentHashMap?

like image 746
Tom Avatar asked Sep 06 '25 18:09

Tom


1 Answers

One difference between the two I came across is that TrieMap.getOrElseUpdate may run the supplied operation multiple times (though at most once per thread calling it) but ConcurrentHashMap.computeIfAbsent does some locking to make sure it only runs once across all threads.

You can try the following code:

(0 to 1000) map { _ =>
  Future { 
    Thread.sleep(100)
    map.getOrElseUpdate(1, {
      Thread.sleep(100)
      counter.incrementAndGet()
    }) 
  }
}

and the counter is most probably not 1, but when tried with concurrentHashMap it is 1.

like image 188
Mahdi Avatar answered Sep 09 '25 18:09

Mahdi