在Akka actor中使用将来的回调 [英] Using future callback inside akka actor

查看:71
本文介绍了在Akka actor中使用将来的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Akka文档中找到了

I've found in Akka docs:

在使用将来的回调(例如onComplete,onSuccess和onFailure)时,在actor内部,您需要小心避免关闭包含的actor的引用,即,不要从回调内部调用方法或访问封闭actor上的可变状态.

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 然后调用一些函数?还是我仍然可以将回调函数与方法一起使用,那我应该如何避免并发错误?

So does it mean that i should always use future pipeTo self and then call some functions? Or i can still use callbacks with method, then how should i avoid concurrency bugs?

推荐答案

这意味着:

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
      }
  }
}

在此示例中,参与者的接收方法和Future的onComplete都更改了可变变量 counter .在这个玩具示例中,它更容易看清,但是Future调用可能是嵌套的方法,这些方法同样捕获了可变变量.

In this example, both the actor's receive method, and the Future's onComplete change the mutable variable counter. In this toy example its easier to see, but the Future call might be nested methods that equally capture a mutable variable.

问题是 onComplete 调用可能在与actor本身不同的线程上执行,因此完全可能让一个线程执行 receive ,而另一个线程执行> onComplete ,从而为您提供了竞争条件.首先,它否定了演员的观点.

The issue is that the onComplete call might execute on a different thread to the actor itself, so its perfectly possible to have one thread executing receive and another executing onComplete thus giving you a race condition. Which negates the point of an actor in the first place.

这篇关于在Akka actor中使用将来的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆