The ScalaDoc says this about concurrentMap: "Deprecated (Since version 2.10.0) Use scala.collection.concurrent.Map instead." Unfortunately, the rest of the Scala docs has not been updated and still references concurrentMap.
I tried to mix in concurrent.Map into a HashMap, with the following results:
scala> val mmap = new mutable.HashMap[String, String] with collection.concurrent.Map[String, String] <console>:16: error: object creation impossible, since: it has 4 unimplemented members. /** As seen from anonymous class $anon, the missing signatures are as follows. * For convenience, these are usable as stub implementations. */ def putIfAbsent(k: String,v: String): Option[String] = ??? def remove(k: String,v: String): Boolean = ??? def replace(k: String,v: String): Option[String] = ??? def replace(k: String,oldvalue: String,newvalue: String): Boolean = ??? val mmap = new mutable.HashMap[String, String] with collection.concurrent.Map[String, String] So we see that instead of a simple mixin, some methods must also be implemented. Is this the best way to use concurrent.Map, or is there a better way?
The scala.collection.concurrent.Map trait is not meant to be mixed-in with an existing mutable Scala Map to obtain a thread-safe version of the map instance. The SynchronizedMap mixin existed for this purpose before 2.11, but is now deprecated.
Currently, Scala has the scala.collection.concurrent.TrieMap implementation for the scala.collection.concurrent.Map interface, but can wrap Java classes as well.
The scala.collection.concurrent.Map, in versions prior to 2.10 known as scala.collection.mutable.ConcurrentMap, interface is used when you:
want to implement your own concurrent, thread-safe Map from scratch
want to wrap an existing Java concurrent map implementation:
E.g:
import scala.collection._ import scala.collection.convert.decorateAsScala._ import java.util.concurrent.ConcurrentHashMap val map: concurrent.Map[String, String] = new ConcurrentHashMap().asScala E.g.:
import scala.collection._ def foo(map: concurrent.Map[String, String]) = map.putIfAbsent("", "") foo(new concurrent.TrieMap) foo(new java.util.concurrent.ConcurrentSkipListMap().asScala) E.g.:
class MySynchronizedMap[K, V](private val underlying: mutable.Map[K, V]) extends concurrent.Map[K, V] { private val monitor = new AnyRef def putIfAbsent(k: K,v: V): Option[String] = monitor.synchronized { underlying.get(k) match { case s: Some[V] => s case None => underlying(k) = v None } } def remove(k: K, v: V): Boolean = monitor.synchronized { underlying.get(k) match { case Some(v0) if v == v0 => underlying.remove(k); true case None => false } } // etc. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With