I need to cache something in Scala in a multi-threaded environment.
Reading up on scalaz's Memo I found the following comment in the code for the immutable hash map memo:
As this memo uses a single var, it's thread-safe.
The code looks like this:
def immutableMapMemo[K, V](m: Map[K, V]): Memo[K, V] = {
var a = m
memo[K, V](f =>
k => {
a get k getOrElse {
val v = f(k)
a = a updated (k, v)
v
}
})
}
Saying that this is thread safe goes against what I have read and learned so far about thread-safety on the JVM-platform; Reference updates may be atomic, but as I have understood it, the compiler may try do certain optimisations that upsets the happens-before relationship if you don't have a memory barrier. See for instance this post and this.
But I'm sure the scalaz folks are pretty smart. Maybe there's something special about the scope of a.
Is what the comment claims true, and if so, why?