我在 Akka 文档中发现:
When using future callbacks, such as onComplete, onSuccess, and onFailure, inside actors you need to carefully avoid closing over the containing actor’s reference, i.e. do not call methods or access mutable state on the enclosing actor from within the callback.
那么这是否意味着我应该始终使用
future pipeTo self
然后调用一些函数?或者我仍然可以使用带有方法的回调,那么我应该如何避免并发错误?
最佳答案
这意味着:
class NotThreadSafeActor extends Actor {
import context.dispatcher
var counter = 0
def receive = {
case any =>
counter = counter + 1
Future {
// do something else on a future
Thread.sleep(2000)
}.onComplete {
_ => counter = counter + 1
}
}
}
在这个例子中,actor 的接收方法和 Future 的 onComplete 都改变了可变变量
counter
.在这个玩具示例中,它更容易看到,但 Future 调用可能是同样捕获可变变量的嵌套方法。问题在于
onComplete
调用可能会在与 actor 本身不同的线程上执行,因此完全有可能让一个线程执行 receive
另一个正在执行 onComplete
从而给你一个竞争条件。这首先否定了 Actor 的观点。
关于scala - 在 akka actor 中使用 future 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23908132/