9

I have been reading some posts and was wondering if someone can present a situation on when a TrieMap would be preferable to using a HashMap.

So essentially what architecture decision should motivate the use of a TrieMap?

1
  • You mean scala.collection.concurrent.TrieMap? Commented Nov 1, 2015 at 21:20

1 Answer 1

9

As per documentation. It's mutable collection that can be safely used in multithreading applications.

A concurrent hash-trie or TrieMap is a concurrent thread-safe lock-free implementation of a hash array mapped trie. It is used to implement the concurrent map abstraction. It has particularly scalable concurrent insert and remove operations and is memory-efficient. It supports O(1), atomic, lock-free snapshots which are used to implement linearizable lock-free size, iterator and clear operations. The cost of evaluating the (lazy) snapshot is distributed across subsequent updates, thus making snapshot evaluation horizontally scalable.

For details, see: http://lampwww.epfl.ch/~prokopec/ctries-snapshot.pdf

Also it has really nice API for caching. So for example you have to calculate factorials of different number and sometimes re-use this results.

  object o {

    val factorialsCache = new TrieMap[Int, Int]()

    def factorial(num: Int) = ??? // really heavy operations
    def doWorkWithFuctorial(num: Int) = {
      val factRes = factorialsCache.getOrElseUpdate(num, {
        // we do not want to invoke it very often
        factorial(num)
           // this function will be executed only if there are no records in Map for such key
      })
      // start do some work `withfactRes`
      factRes
    }
  }

Pay attention - function above use global state (cache) for write operations, but it's absolutely safe to use it in concurrent threads. You'll not loose any data.

0

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