alifirat alifirat - 5 months ago 47
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 = {
system = ActorSystem("SysActor")

override def onStop(app: Application) : Unit = {
if (system != null) {
system.terminate + " 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.


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 + " shutdown !")


  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)