ayvango
ayvango

Reputation: 5977

correctly terminate akka actors in scala

I've write sample code that starts an actor, kills it and finishes execution.

object PureAkka {
  def main(argv : Array[String]) = {
    val actorSystem : ActorSystem = ActorSystem("main")
    val actor : ActorRef = actorSystem.actorOf(Props( new Actor {
      override def receive = {
        case x => println(x)
      }
      override def preStart() = println("prestart")
      override def postStop() = println("poststop")
    } ) )
    Thread.sleep(15000)
    actor ! PoisonPill
  }
}

This code prints:

[info] prestart
[info] poststop

But it refuses to stop until I kill the process with Ctrl-C

What does application wait for? How can I stop it in a proper way?

Upvotes: 5

Views: 4468

Answers (1)

Garrett Bluma
Garrett Bluma

Reputation: 1312

Perhaps making a call to ActorSystem.shutdown() would do the trick.

According to the akka docs:

abstract def shutdown(): Unit

Stop this actor system. This will stop the guardian actor, which in turn will recursively stop all its child actors, then the system guardian (below which the logging actors reside) and the execute all registered termination handlers (see ActorSystem.registerOnTermination).

Upvotes: 8

Related Questions