I disagree with the above advise. If you are going to have mutable state anyway, you are better off isolating it inside the data container rather than replacing the container itself every time.
You are better off using java containers for this purpose. For a hashmap, java ConcurrentHashMap
is your best choice. For a sorted implementation, you'll have to synchronize explicitly:
object DB {
import java.util._
val hashed = new concurrent.ConcurrentHashMap[String, AnyRef]
val sorted = Collections.synchronizedMap(new TreeMap[Int, AnyRef])
}
You can import scala.collection.JavaConversions._
to implicitly convert those into scala Maps, to get goodies, like map
, filter
etc., But ... you probably should not. Using any of those wouldn't be a good idea under concurrency in 99% of cases. Anything, other than you regular get
and put
(and, put/computeIfNotExists
for the ConcurrentHashmap
case) primitives would be non-trivial to implement and dangerous to use.
Think of these as just primitive key-value containers, not full-blown scala collections.