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?

2
  • > I don't understand what consistent here really means. The following question has details on 'consistent' iterator: stackoverflow.com/questions/29499381/…
    – FabFlying
    Commented Aug 8, 2017 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)). Commented Aug 8, 2017 at 13:10

1 Answer 1

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.

3
  • 3
    I think this changed in version 2.11.6. According to docs: "Note: This method will invoke op at most once...." see: scala-lang.org/api/2.11.6/…
    – fonkap
    Commented Jan 8, 2020 at 16:19
  • Both methods are atomic and doing the same job: putIfAbsent and getOrElseUpdate
    – NKM
    Commented Oct 29, 2021 at 5:34
  • @fonkap your link is outdated, here is a better one: github.com/scala/scala/pull/4319
    – Nick
    Commented Dec 20, 2022 at 8:47

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