简体   繁体   English

akka getSender()将来会丢失

[英]akka getSender() lost in future

I have a problem in akka (java) with the reference of the sender which disappears after a while in a future. 我在akka(java)中遇到了发件人的引用问题,以后会在一段时间后消失。 Here is the code: 这是代码:

class MyActor extends UntypedActor {
  @Override
  public void onReceive(Object msg){
    Future<Integer> future = Futures.future(new Callable<Integer>(){
      @Override
      public Integer call() throws Exception {
        System.out.println(getSender()); //works fine
        Thread.sleep(1000);
        System.out.println(getSender()); //show deadLetter
        return 42;
      }
    },getContext().dispatcher());

    //do something with the future, pipe it or whatever
    Patterns.pipe(future,getContext().dispatcher(),getSender());
  }
}

I might have missed something in the doc. 我可能错过了文档中的某些内容。

It is explained in the Actors, section of the docs with a big warning sign: 在文档的Actors部分中对此进行了解释,并带有一个大警告符号:

Warning When using future callbacks, inside actors you need to carefully avoid closing over the containing actor's reference, ie do not call methods or access mutable state on the enclosing actor from within the callback. 警告使用将来的回调时,在Actor内部,您需要小心避免关闭包含的Actor的引用,即,不要从回调内部调用方法或访问封闭Actor上的可变状态。 This would break the actor encapsulation and may introduce synchronization bugs and race conditions because the callback will be scheduled concurrently to the enclosing actor. 这将破坏参与者的封装,并且可能会引入同步错误和竞争条件,因为回调将同时安排到封闭的参与者。 Unfortunately there is not yet a way to detect these illegal accesses at compile time. 不幸的是,还没有一种在编译时检测到这些非法访问的方法。 See also: Actors and shared mutable state 另请参阅:参与者和共享的可变状态

It is also explained here: 这里也作了解释:

http://doc.akka.io/docs/akka/2.0.2/general/jmm.html#jmm-shared-state http://doc.akka.io/docs/akka/2.0.2/general/jmm.html#jmm-shared-state

When you close over "getSender()" you're really closing over "this.getSender()", which means that you're closing over the internal state of the actor, which the docs above tells you not to. 当您关闭“ getSender()”时,实际上是在关闭“ this.getSender()”,这意味着您正在关闭actor的内部状态,上面的文档告诉您不要这么做。

I will add this to our FAQ. 我将其添加到我们的常见问题解答中。

Happy hAkking, 祝你开心

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM