Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for Akka actor system to terminate?

Tags:

scala

akka

I need to start Akka (2.0) actor system, send in some messages, then wait for it to do heavy lifting. After that, I need to do something unrelated to those actors.

I tried to wait for all actors to stop with following code:

val system = new ActorSystem("parallelRunners")
val master = system.actorOf(Props[Master])
master ! Start
system.awaitTermination // <-- hangs here

All actors kill themselves via self ! PoisonPill. What am I doing wrong?

like image 686
Rogach Avatar asked Sep 15 '12 09:09

Rogach


People also ask

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.

Is Akka actor thread safe?

Actors are 'Treadsafe'. The Actor System (AKKA), provides each actor with its own 'light-weight thread'. Meaning that this is not a tread, but the AKKA system will give the impression that an Actor is always running in it's own thread to the developer.


2 Answers

In Akka 2.4.1 for scala 2.11 it appears to be different again.

system.awaitTermination() is deprecated and the docs instruct us to use Await.result(system.whenTerminated, timeout) instead.

As 203 said, system.terminate is still the way to terminate the system.

Here is some example code I used:

val actorSystem = ActorSystem("ActorSystem")
val myActors = actorSystem.actorOf(Props[MyActor].withRouter(RoundRobinPool(10)), "MyActors")
rainbows.foreach(rainbow => myActors ! rainbow)
Await.ready(actorSystem.whenTerminated, Duration(1, TimeUnit.MINUTES))

Then in the MyActor class I have the line context.system.terminate()

like image 89
Michael Larsen Avatar answered Oct 13 '22 19:10

Michael Larsen


As of Akka 2.4, you should use system.awaitTermination() which returns a Future[Terminated] you can wait for.

In order to terminate the system, you should use ActorSystem.terminate (e.g. context.system.terminate() from within an actor when it is finished.

Source: Release Notes

like image 29
203 Avatar answered Oct 13 '22 18:10

203