alifirat alifirat - 1 month ago 13
Scala Question

Scala application lifecycle

Recently I changed a Play application using Akka Actors to a classic Scala application. With Play, I override the global settings of the app like this :

import play.api._
import play.api.Play.current

object Global extends GlobalSettings {
var system: ActorSystem = _

override def onStart(app: Application) : Unit = {
super.onStart(app)
Logger.info("onStart")
system = ActorSystem("SysActor")

override def onStop(app: Application) : Unit = {
super.onStop(app)
if (system != null) {
system.terminate
Logger.info(system + " shutdown !")
}
}
}


In a classic scala application, I defined a main class to be executed at
sbt run
command but is it a way to detect, like
Play Scala
, the close or stop of the running app ? Note that I published the app on Amazon EC2 using Docker.

Answer

One way to do it would be to register a shutdown hook, something like:

object MyApp {

  val system = ActorSystem("SysActor") // instantiation can be moved to main

  private val t = new Thread { 
    override def run() = {
      if (system != null) {
        system.terminate
        Logger.info(system + " shutdown !")
      }
    }        
  }

  Runtime.getRuntime.addShutdownHook(t)

  def main(args: Array[String]): Unit = { ... }

}    

Shutdown hooks are called when the JVM gets a shutdown signal (although note that it's not guaranteed, depending on the signal)