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?
I found the solution - just call system.shutdown from the master actor:
in Akka 2.3.9, it seems that shutting down an actor system and waiting for it to shut down is a two step process:
actorSystem.shutdown
actorSystem.awaitTermination
As an alternative to step (2), possibly (haven't tested these alternatives) you may alternatively poll on
isTerminated
or useregisterOnTermination
for running some code when it's terminated. So it is worth going through the comments of akka.actor.ActorSystem to fathom and choose between these methods for your implementation.Perhaps I'm missing other options about the API (?) as
Future
return values could have been nicer.Just a side note for those running into this question for its title: Apparently, Akka 2.5 does not support
actorSystem.awaitTermination
anymore. Reason being why might be Akka's philosophy of avoiding any blocking calls. Instead,actorSystem.registerOnTermination(...)
can be used as a non-blocking way to do actions while anActorSystem
is being shutdown.Nonetheless, you can still wait for your actor system to complete via a
Future
provided byActorSystem.whenTerminated
: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 useAwait.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:
Then in the MyActor class I have the line
context.system.terminate()
As of Akka 2.4, you should use
system.awaitTermination()
which returns aFuture[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
How about:
terminate returns a Future:
and you can just await completion of this future.