title: How do I wait for an actor to stop during Play Framework shutdown?
body: <p>The below code throws a <strong>java.lang.IllegalMonitorStateException</strong> exception when I shutdown the play server; it is caused by the <strong>a.wait(1000)</strong> call in the <strong>onStop</strong> method. Could anyone tell me why this is the case and how to gracefully wait for an actor to complete within Play framework shutdown?</p>
  
  <pre><code>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()
      }
  }
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <p>Here is the complete solution, taking the below answer:</p>
  
  <pre><code>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 =&gt; // the actor wasn't stopped within 5 seconds
          }
  
          Akka.system.shutdown()
          Akka.system.awaitTermination()
      }
  }
  </code></pre>