Get existing or create new akka actor

后端 未结 3 1630
生来不讨喜
生来不讨喜 2020-12-31 17:33

I\'m trying to get an existing ActorRef with ActorFor or create a new one if it does not exists. I have the following code but it doesn\'t seem to work as expected. .isTermi

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 18:03

    Get-or-create can only be performed by the parent of the designated actor, since only that parent can create the actor if it does not exist, and only the parent can do so consistently (i.e. without race conditions). Within an actor you can do

    // assuming a String name like "fred" or "barney", i.e. without "/"
    final Option child = child(name);
    if (child.isDefined())
      return child.get();
    else
      return getContext().actorOf(..., name);
    

    Do not do this at the top-level (i.e. using system.actorOf), because then you cannot be sure who “wins” in requesting creation and also relying on the user guardian is not good a good supervision strategy.

提交回复
热议问题