4

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?

Tom
  • 5,848
  • 12
  • 44
  • 104
  • > I don't understand what consistent here really means. The following question has details on 'consistent' iterator: https://stackoverflow.com/questions/29499381/what-is-a-triemap-and-what-is-its-advantages-disadvantages-compared-to-a-hashmap – FabFlying Aug 08 '17 at 13:04
  • A consistent iterator means that it will be able to provide a snapshot of the `TrieMap` at the point you request a snapshot, or an iterator. If you read the guarantee you get from `ConcurrentHashMap`, it says: *Iterators and Enumerations return elements reflecting the state of the hash table **at some point at or since the creation of the iterator/enumeration***, which I'm not sure is what you want. Also, iterators over `TrieMap` should be very fast to retrieve (O(1)). – Yuval Itzchakov Aug 08 '17 at 13:10

1 Answers1

3

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.

Mahdi
  • 1,778
  • 1
  • 21
  • 35
  • 2
    I think this changed in version 2.11.6. According to docs: "Note: This method will invoke op at most once...." see: https://www.scala-lang.org/api/2.11.6/index.html#scala.collection.concurrent.TrieMap – fonkap Jan 08 '20 at 16:19
  • Both methods are atomic and doing the same job: putIfAbsent and getOrElseUpdate – NKM Oct 29 '21 at 05:34
  • @fonkap your link is outdated, here is a better one: https://github.com/scala/scala/pull/4319 – Nick Dec 20 '22 at 08:47