Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correctly terminate akka actors in scala

Tags:

scala

akka

actor

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?

like image 236
ayvango Avatar asked Sep 07 '12 19:09

ayvango


People also ask

How do I terminate Akka actor?

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.

How do you stop an actor in Scala?

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.

Can an Akka actor stop itself?

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.

What happens when an actor fails in Akka?

When an actor throws an unexpected exception, a failure, while processing a message or during initialization, the actor will by default be stopped.


1 Answers

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).

like image 151
Garrett Bluma Avatar answered Oct 05 '22 07:10

Garrett Bluma