3

当我关闭播放服务器时,以下代码会引发java.lang.IllegalMonitorStateException异常;它是由onStop方法中的a.wait(1000)调用引起的。谁能告诉我为什么会这样以及如何优雅地等待演员在 Play 框架关闭中完成?

import play.api.GlobalSettings
import play.api.libs.concurrent.Akka
import akka.actor.{ Actor, Props }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.Play.current
import models.{ TestActor, StartMessage, StopMessage }

object Global extends GlobalSettings {

    override def onStart(application : play.api.Application) {
        val a = Akka.system.actorOf(Props[TestActor], name = "test-actor")
        a ! StartMessage("Start instruction")

    }

    override def onStop(application : play.api.Application) {
        val a = Akka.system.actorSelection("akka://application/user/test-actor")
        a ! StopMessage("Stop instruction")
        a.wait(1000)
        Akka.system.shutdown()
    }
}

更新:

这是完整的解决方案,采用以下答案:

import play.api.GlobalSettings
import play.api.libs.concurrent.Akka
import akka.actor.{ Actor, Props }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.Play.current
import models.{ TestActor, StartMessage, StopMessage }
import akka.pattern.gracefulStop
import scala.concurrent.Future
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.Await
import com.typesafe.config.impl.ResolveContext
import com.typesafe.config.impl.ResolveContext
import akka.actor.ActorIdentity

object Global extends GlobalSettings {

    override def onStart(application : play.api.Application) {
        val a = Akka.system.actorOf(Props[TestActor], name = "test-actor")
        a ! StartMessage("Start Instruction")
    }

    override def onStop(application : play.api.Application) {
        val a = Akka.system.actorFor("akka://application/user/test-actor")
        a ! StopMessage("Stop Instruction")

        try {
            val stopped : Future[Boolean] = gracefulStop(a, scala.concurrent.duration.Duration(5, "seconds"))
            Await.result(stopped, scala.concurrent.duration.Duration(6, "seconds"))
            // the actor has been stopped
        }
        catch {
            case e : akka.pattern.AskTimeoutException => // the actor wasn't stopped within 5 seconds
        }

        Akka.system.shutdown()
        Akka.system.awaitTermination()
    }
}
4

1 回答 1

7

“如果您需要等待终止或组合多个参与者的有序终止,Graceful Stop GracefulStop 很有用:

import akka.pattern.gracefulStop
import akka.dispatch.Await
import akka.actor.ActorTimeoutException

try {
  val stopped: Future[Boolean] = gracefulStop(actorRef, 5 seconds)(system)
  Await.result(stopped, 6 seconds)
  // the actor has been stopped
} catch {
  case e: ActorTimeoutException ⇒ // the actor wasn't stopped within 5 seconds
}

"

PS。谷歌搜索“优雅的演员 akka”给出了最佳结果。

于 2013-10-17T00:46:30.003 回答