scala - 在 akka actor 中使用 future 回调

标签 scala concurrency callback akka future

我在 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/

相关文章:

scala - Slick中的inSet和inSetBind有什么区别

java - 在 Scala 中通过 SimpleDateFormat 转换后如何保持 DateTime 为 DateTime 格式?

scala - 在哪里获取提供 scala.tools.nsc.MainGenericRunner 的 jar

java - Junit 测试并发

c# - 在回调中使用 await

scala - Scala 中的按名称调用与 Haskell 中的惰性求值?

java - 具有非常具体要求的高性能、无锁 Java 集合

java - singlethreadexecutor - 多线程 java

php - 如何使用类方法作为回调

types - 定义 TypeScript 回调类型