该ScalaDoc "已过时(从版本2.10.0)使用:说这约concurrentMap scala.collection.concurrent.Map来代替." 不幸的是,Scala文档的其余部分尚未更新,仍然引用concurrentMap.
我尝试混入concurrent.Map一个HashMap,结果如下:
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] …Run Code Online (Sandbox Code Playgroud) 我想知道是否有任何'简单'的方法来安全地更新不可变的scala集合.考虑以下代码:
class a {
private var x = Map[Int,Int]()
def update(p:(Int,Int)) { x = x + (p) }
}
Run Code Online (Sandbox Code Playgroud)
这段代码不是线程安全的,对吗?我的意思是,如果我们有两个线程调用update方法,并且假设x是包含{1 => 2}的映射,并且线程A调用update((3,4))并且只设法执行x +(p)部分代码.然后重新安排,线程B调用update((13,37))并成功更新变量x.线程A继续并结束.
完成所有这些后,值x将等于包含{1 => 2,3 => 4}的地图,对吗?而不是期望的{1 => 2,3 => 4,13 => 37}.有没有一种简单的方法来解决这个问题?我希望我的要求是不可靠的:)
顺便说一句,我知道有像Akka STM这样的解决方案,但除非必要,否则我宁愿不使用它们.
非常感谢您的回答!
编辑:另外,我更喜欢没有锁定的解决方案.Eeeew :)