0

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.

cchantep
  • 9,118
  • 3
  • 30
  • 41
alifirat
  • 2,899
  • 1
  • 17
  • 33

1 Answers1

1

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)

Community
  • 1
  • 1
Tzach Zohar
  • 37,442
  • 3
  • 79
  • 85
  • So the call to `addShutdownHook` implicitly shutdown the actor system of my app ? – alifirat Oct 31 '16 at 09:20
  • No, sorry - I wasn't clear - your implementation of the `run` method in the thread you're passing to `addShutdownHook` should do whatever needs to be done upon shutdown; In your case, it should call `system.terminate` – Tzach Zohar Oct 31 '16 at 09:22
  • Or one line `sys.addShutdownHook(system.shutdown())` if `val system = ActorSystem(...)` – andrey.ladniy Nov 01 '16 at 17:51