0

我有一个actorsystem,我在其中注册了一些关于actorsystem终止的代码。代码如下 -

object ChildActor {
  class Msg
}

class ChildActor extends Actor {
  val log = Logging(context.system, this)

  override def receive: Receive = {
    case a : String => log.info(s"received $a")
    case _ : Msg => throw new OutOfMemoryError("error")
  }
}

class ParentActor extends Actor {
  override val supervisorStrategy = OneForOneStrategy() {
    case _: OutOfMemoryError => {
      Stop
    }
    case _: Exception => Stop
  }
  val child = context.actorOf(Props[ChildActor], "child")
  override def receive: Receive = {
    case a: String => child ! a
    case msg : Msg => child ! msg
  }
}

object Test extends App {

  val customConf = ConfigFactory.parseString("""
  akka {
    jvm-exit-on-fatal-error = false
  }
  """)


  val actorSystem = ActorSystem("OOMException", ConfigFactory.load(customConf))

  actorSystem.registerOnTermination(println("going off"))

  val actor = actorSystem.actorOf(Props[ParentActor], "parentActor")

  actor ! new Msg

}

我注意到的奇怪行为是我的回调。当我正常运行应用程序时,我永远不会收到注册代码的回调。

但是,当我在调试模式下运行并在terminate()方法中等待几秒钟然后该行被打印出来.. 我不确定为什么这几秒钟的等待是确保在正常运行时触发所有注册的回调模式没有发生..有人知道吗?

PS:我知道 OOM 是致命的,但我只是对手头的问题感到好奇,OOM 只是一种情况。

当我在最后进行线程转储时,我看到始终存在以下两个线程 -

"OOMException-akka.actor.default-dispatcher-2" #12 prio=5 os_prio=0 tid=0x000000001e8dd800 nid=0x1029c waiting on condition [0x0000000020eff000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000770700c90> (a akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinPool)
    at akka.dispatch.forkjoin.ForkJoinPool.scan(ForkJoinPool.java:2075)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

"OOMException-scheduler-1" #11 prio=5 os_prio=0 tid=0x000000001e5d8800 nid=0xfba4 waiting on condition [0x000000001f35e000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at akka.actor.LightArrayRevolverScheduler.waitNanos(LightArrayRevolverScheduler.scala:85)
    at akka.actor.LightArrayRevolverScheduler$$anon$4.nextTick(LightArrayRevolverScheduler.scala:265)
    at akka.actor.LightArrayRevolverScheduler$$anon$4.run(LightArrayRevolverScheduler.scala:235)
    at java.lang.Thread.run(Thread.java:748)

当参与者系统终止时,调度程序应该已经完成​​..不确定为什么它处于定时等待状态..

4

1 回答 1

1

App在这里可能会很棘手,也许 JVM 在你的回调被执行之前就被终止了(因为剩下的所有线程都是守护线程)。

我首先建议将您的应用程序代码放入一个def main(...)方法中。

使用类似这样的东西而不是println

val promise = Promise.empty[Unit]
actorSystem.registerOnTermination(promise.success(()))
val actor = actorSystem.actorOf(Props[ParentActor], "parentActor")
actor ! new Msg
Await.ready(promise.future, Duration.INF)
println("going off")
于 2018-04-11T10:07:09.807 回答