当我关闭播放服务器时,以下代码会引发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()
}
}