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?
In Akka, you can stop Actors by invoking the stop() method of either ActorContext or ActorSystem class. ActorContext is used to stop child actor and ActorSystem is used to stop top level Actor. The actual termination of the actor is performed asynchronously.
You can also stop an actor by sending it a PoisonPill message. This message will stop the actor when the message is processed. The message is queued in the mailbox like an ordinary message.
An actor can stop itself by returning. Behaviors. stopped as the next behavior. A child actor can be forced to stop after it finishes processing its current message by using the stop method of the ActorContext from the parent actor.
When an actor throws an unexpected exception, a failure, while processing a message or during initialization, the actor will by default be stopped.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With