Not a full answer to your question, but…
Either 1 or 2 in your question would not be fit for a multi-threaded environment — val
s with immutable data structures are. For multi-threaded access to mutable collections, I'd still recommend Java's collections from the java.util.concurrent
package. E.g., to create a mutable, concurrent hash map:
def emptyConcurrentHashMap[K, V] = {
import collection.JavaConverters._
new java.util.concurrent.ConcurrentHashMap[K, V].asScala
}
You still get the more idiomatic Scala accessors like this, and you'd use the special atomic mutator methods (like def putIfAbsent(k: A, v: B): Option[B]
and def replace(k: A, oldvalue: B, newvalue: B): Boolean
).
Alternatively, you could use an AtomicReference
that holds an immutable collection, and replace it with its compareAndSet
method.