sungiant
sungiant

Reputation: 3222

Shutting down an Akka Actor system from an Actor

I know I can use system.shutdown() outside of an actor system to stop the actor system and make system.awaitTermination() stop blocking execution on its thread.

I want to trigger the actor system shutdown from within one of my Actors. I thought I should be able to call context.system.shutdown() from within an Actor's receive method, however when I do this nothing seems to happen, system.awaitTermination() (on the main thread) just keeps on blocking.

Any ideas?

Upvotes: 4

Views: 2234

Answers (3)

Andriy Plokhotnyuk
Andriy Plokhotnyuk

Reputation: 7989

Main Thread:

val l = new CountDownLatch(1)
val s = ActorSystem("system", config)
...
//create some actors and send some messages to them
...
l.await()
s.shutdown()
s.awaitTermination()

Some where in def receive: Actor.Receive:

l.countDown()

Upvotes: 0

user644265
user644265

Reputation: 301

How to program an Actor to kill self

class WatchActor extends Actor {

   val child = context.actorOf(Props.empty, "child")
   context.watch(child) // <-- this is the only call needed for registration
   var lastSender = system.deadLetters

def receive = {
  case "kill" =>
   context.stop(child); lastSender = sender()
   case Terminated(`child`) => lastSender ! "finished"
  }
}

At this url there is a good explain.

http://doc.akka.io/docs/akka/snapshot/scala/actors.html

jfm

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53809

You should not do that: it is like a snake biting its own tail.

system.awaitTermination() will keep blocking because you are precisely waiting for it to end!

You can perfectly call context.system.shutdown() within an actor, but you cannot call system.awaitTermination() in the actor system context. And also it does not make a lot of sense: why would you wait since there is anyway nothing to execute afterwards, the system being down?

Blocking on the system to shut down makes sense outside of it only, if you want to execute further instructions after it has been stopped.

Upvotes: 0

Related Questions