I am using actors to parallelize some work. I am creating a list of actors and sending messages randomly to them.
val actors = Range(1, threads + 1).map(_ => new MyActor)
actors.foreach(a => a.start)
val messages: List[String] = getMessages()
messages.foreach { m =>
actors((Math.random() * actors.size).toInt) ! m
}
actors.foreach(_ ! "KILLME")
var exit = false
while (!exit) {
Thread.sleep(1000L)
exit = actors.foldLeft(true) { (ac, imp) =>
ac && (imp.getState.toString == "Terminated")
}
}
This is the actor code:
def act {
while (true) {
receive {
case "KILLME" => return
case m: String => doSomeComplexThingWith(m)
}
}
}
If I run this code, the app will run forever, until I force to quit it. I want the app to stop after all messages were processed by the group of actors. Is there any way to detect that all actors are not working for some time and finish the application then?