Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it appropriate to use a TrieMap?

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?

like image 959
toidiu Avatar asked Nov 01 '15 18:11

toidiu


1 Answers

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.

like image 136
vvg Avatar answered Oct 10 '22 14:10

vvg