this vs self inside akka actor class

this vs self inside akka actor class

假设我有一个非常简单的 actor class,它接收任何消息并打印到控制台。

  class SimpleActor extends Actor{

    def receive: Receive = {
      case message =>
        println(s"[${this}][${self}] received message: ${message}")
    }
  }

  val simpleActor = actorSystem.actorOf(Props[SimpleActor], "simpleActor")
  simpleActor ! "Hey"

如您所见,我在这里同时使用了 thisself,两者具有不同的值。它的输出是这样的:

[pkg.ActorRunner$SimpleActor@65cca69][Actor[akka://ActorDemo/user/simpleActor#934141660]] received message: Hey

我想了解 selfthis 之间的区别,因为在复杂的场景(生产系统)中,如果 actor 中断,例如:抛出异常比我认为 [=13 的值=] 被改变。

this 是对扩展 Actor 特征的对象的经典 java 引用,而 self 是对 ActorRef 的引用,这正是您需要的发送消息(!tell?ask

  • 您无法向 this
  • 发送消息
  • 您不应该在演员外部传递对 this 的引用,而传递对 self 的引用是完全可以的,事实上,当您从另一个演员向演员发送消息时,它是隐式发送的。如果您将 this 传递给另一个对象,您将面临参与者状态封装的风险。请记住,与演员交流的唯一方式是通过消息,即使用其 ActorRef
  • self 将在 actor 重启后保持有效,也就是您可以继续向同一个 ActorRef(自己)发送消息。只有当 actor 停止时,对 ActorRef 的引用才不再有效,发送到该地址的消息将以死信结尾。
  • this 在 actor 重启后将不再有效。实例化一个类型为 Actor 的新对象,以清除可能因失败而受到损害的参与者状态。

What restarting means

Unless the failure is specifically recognizable, the third cause cannot be ruled out, which leads to the conclusion that the internal state needs to be cleared out. If the supervisor decides that its other children or itself is not affected by the corruption—e.g. because of conscious application of the error kernel pattern—it is therefore best to restart the child. This is carried out by creating a new instance of the underlying Actor class and replacing the failed instance with the fresh one inside the child’s ActorRef; the ability to do this is one of the reasons for encapsulating actors within special references. The new actor then resumes processing its mailbox, meaning that the restart is not visible outside of the actor itself with the notable exception that the message during which the failure occurred is not re-processed.

Actor Reference and Path Equality

Note that a restart of an actor caused by a failure still means that it is the same actor incarnation, i.e. a restart is not visible for the consumer of the ActorRef.

What is the Difference Between Actor Reference and Path?

An actor reference designates a single actor and the life-cycle of the reference matches that actor’s life-cycle; an actor path represents a name which may or may not be inhabited by an actor and the path itself does not have a life-cycle, it never becomes invalid. You can create an actor path without creating an actor, but you cannot create an actor reference without creating corresponding actor.
You can create an actor, terminate it, and then create a new actor with the same actor path. The newly created actor is a new incarnation of the actor. It is not the same actor. An actor reference to the old incarnation is not valid for the new incarnation. Messages sent to the old actor reference will not be delivered to the new incarnation even though they have the same path.