【问题标题】:Akka Supervision default behaviorAkka 监督默认行为
【发布时间】:2019-01-17 02:01:03
【问题描述】:

我正在尝试学习 Akka 监督策略。当我有下面这样的代码时,我确实得到了这个

java.lang.ArithmeticException: / 为零

case object CreateChildren
case class DivideNumbers(n: Int , d:Int)
object SuperVision extends App {
  val actorSystem = ActorSystem("SupervisingActorSystem")
  val actor = actorSystem.actorOf(Props[ParentActor], "ParentActor")
  actor ! CreateChildren
  val child1 = actorSystem.actorSelection("/user/ParentActor/childActor")
  child1 ! DivideNumbers(4,0)

class ParentActor extends Actor{
  override def receive: Receive = {
    case CreateChildren =>
      context.actorOf(Props[ChildActor], "childActor")
  }
}

  class ChildActor extends Actor{
    override def receive: Receive = {
      case DivideNumbers(n,d) => println(n/d)

    }
  }

  actorSystem.terminate()
}

但是当我没有创建子 Actor 并且有类似的东西时,我看不到异常。

val actorSystem = ActorSystem("SupervisingActorSystem")
  val actor = actorSystem.actorOf(Props[ParentActor], "ParentActor")
  actor ! DivideNumbers(4, 2)

  class ParentActor extends Actor {
    override def receive: Receive = {
      case DivideNumbers(n, d) => println(n / d)
      //case DivideNumbers(n, d) => throw new Exception
      //Even this doesn't throw an exception
    }
  }

  actorSystem.terminate()
  1. 为什么我没有看到异常,是我遗漏了什么吗?
  2. 这背后的原因是什么 行为?
  3. 什么是处理异常的好方法? 只有一位演员没有孩子?

【问题讨论】:

    标签: scala akka


    【解决方案1】:

    您没有收到异常只是因为在引发异常之前您的演员系统已经终止,然后应用程序退出。

    尝试在actorSystem.terminate()之前添加Thread.sleep(1000),你会看到异常。

    顺便说一句:此行为与if you use only one actor or with a child 无关。如果您使用孩子只是因为它是与时间顺序相关的随机行为,则会出现异常。

    【讨论】:

    • 啊!谢谢!那行得通。任何 cmets 为什么在第一个示例中没有时间问题?
    • 你很少看到它,因为terminate需要更多时间杀死2个actor,它比唯一一个actor需要更多时间,所以你有机会看到异常,但不要依赖就可以了。
    • 感谢您的快速解答。认为最好将 terminate 移动到 postStop 方法中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2017-03-10
    • 2014-09-12
    • 2018-03-17
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多