Using getOrElseUpdate of TrieMap in Scala

731 Views Asked by At

I am using the getOrElseUpdate method of scala.collection.concurrent.TrieMap (from 2.11.6)

 // simplified for clarity

 val trie = new TrieMap[Int, Future[String]]

 def foo(): String = ... // a very long process

 val fut: Future[String] = trie.getOrElseUpdate(id, Future(foo()))

As I understand, if I invoke the getOrElseUpdate in multiple threads without any synchronization the foo is invoked just once.

Is it correct ?

1

There are 1 best solutions below

0
On BEST ANSWER

The current implementation is that it will be invoked zero or one times. It may be invoked without the result being inserted, however. (This is standard behavior for CAS-based maps as opposed to ones that use synchronized.)