Scala 中的多线程——只处理不变性 [英] Multi-threading in Scala -- dealing only with immutability
问题描述
我有Scala的代码
class MyClass {
private val myData: Map[String, MyClass2] = new HashMap[String, MyClass2]()
def someMethod = {
synchronized(myData) {
val id = getSomeId
if (myData.containsKey(id)) myData = myData.remove(id)
else Log.d("123", "Not found!")
}
}
def getSomeId = //....
}
我想知道,是否有可能在不使用 synchronized
并且不涉及其他一些库(例如 Akka
或任何其他库)的情况下保持此代码线程安全strong>(类)甚至内置在 Java 或 Scala 中?
I wonder, is it possible to remain this code thread-safe without using synchronized
and without involving some other libraries such Akka
or any other libraries (classes) even built-in in Java or Scala?
理想情况下,我只想通过使用不变性的概念(Java 中的 final
,如果您愿意)来使线程安全.
Ideally, I'd like to make thread-safe only by using the conception of immutability (final
in Java, if you will).
更新:
class MyClass(myData: Map[String, MyClass2] = new HashMap[String, MyClass2]()) {
def someMethod = {
synchronized(myData) {
val id = getSomeId
if (myData.containsKey(id)) new MyClass(myData.remove(id))
else {
Log.d("123", "Not found!")
this
}
}
}
def getSomeId = //....
}
推荐答案
只有让 MyClass
也是不可变的(并且让它只使用不可变的数据结构),你才能解决不变性问题.原因很简单:如果MyClass
是可变的,那么你必须通过并发线程同步修改.
You can solve the problem with immutability only if you make MyClass
immutable too (and let it use only immutable data structures as well). The reason is simple: If MyClass
is mutable, then you have to synchronize modifications by concurrent threads.
这需要不同的设计 - 每个导致 MyClass
实例更改"的操作都将返回一个(可能)修改过的实例.
This requires a different design - every operation that causes an instance of MyClass
to "change" will instead return a (possibly) modified instance.
import collection.immutable._
class MyClass2 {
// ...
}
// We can make the default constructor private, if we want to manage the
// map ourselves instead of allowing users to pass arbitrary maps
// (depends on your use case):
class MyClass private (val myData: Map[String,MyClass2]) {
// A public constructor:
def this() = this(new HashMap[String,MyClass2]())
def someMethod(id: String): MyClass = {
if (myData.contains(id))
new MyClass(myData - id) // create a new, updated instance
else {
println("Not found: " + id)
this // no modification, we can return the current
// unmodified instance
}
}
// other methods for adding something to the map
// ...
}
这篇关于Scala 中的多线程——只处理不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!