2

I need a simple thread-safe in-memory cache in my Scala application.

I need a data structure which support this operation from scala.collection.mutable.MapLike:

def getOrElseUpdate(key: A, op: => B)

and I want this operation to be atomic. Is this operation atomic in scala.collection.concurrent.TrieMap? Or should I use some other data structure?

I use Scala 2.10, but will probably upgrade to 2.11 soon.

I don't want to use scala.collection.mutable.SynchronizedMap, since it is deprecated in Scala 2.11.

2 Answers 2

4

TrieMap is appropriate for such a case

A concurrent hash-trie or TrieMap is a concurrent thread-safe lock-free implementation of a hash array mapped trie.

And getOrElseupdate in TrieMap is thread-safe to use. So yes you should use it. As per this, triemap is actually awesome when the insertion rate is really high. Though the difference can be hardly observed.

1

Alas, TrieMap does not override getOrElseUpdate, which makes this method not thread safe.

SI-7943 TrieMap method getOrElseUpdate is not thread-safe

1

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