什么时候适合使用 TrieMap?
When is it appropriate to use a TrieMap?
我一直在阅读一些帖子,想知道是否有人可以介绍一下 TrieMap 何时比使用 HashMap 更可取的情况。
那么本质上,什么样的架构决策应该激发 TrieMap 的使用?
根据文档。
它是可变集合,可以安全地用于多线程应用程序。
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.
详情见:http://lampwww.epfl.ch/~prokopec/ctries-snapshot.pdf
caching
API 也非常好。
因此,例如,您必须计算不同数字的阶乘,有时会重复使用此结果。
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
}
}
注意 - 上面的函数使用全局状态(缓存)进行写操作,但在并发线程中使用它是绝对安全的。您不会丢失任何数据。
我一直在阅读一些帖子,想知道是否有人可以介绍一下 TrieMap 何时比使用 HashMap 更可取的情况。
那么本质上,什么样的架构决策应该激发 TrieMap 的使用?
根据文档。 它是可变集合,可以安全地用于多线程应用程序。
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 hasparticularly scalable concurrent
insert and remove operations and ismemory-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.
详情见:http://lampwww.epfl.ch/~prokopec/ctries-snapshot.pdf
caching
API 也非常好。
因此,例如,您必须计算不同数字的阶乘,有时会重复使用此结果。
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
}
}
注意 - 上面的函数使用全局状态(缓存)进行写操作,但在并发线程中使用它是绝对安全的。您不会丢失任何数据。