0

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?

Daniel Cukier
  • 11,502
  • 15
  • 68
  • 123
  • 2
    broadcast an [order](http://stackoverflow.com/q/13847963/298389) to perform suicide once you have done with sending your work messages – om-nom-nom Feb 25 '14 at 20:35
  • You might like to look at Akka actors instead, I believe these are replacing Scala actors in Scala 2.10 anyway. When you are finished with Akka actors, you can just shutdown the entire Actor system, of course you have the option of stopping each actor individually as well from it's parent actor. As a bouns you would not need the nasty `while(true)` in each Akka actor either. – adamretter Feb 25 '14 at 23:40
  • @om-nom-nom I added the broadcast suicide message. – Daniel Cukier Mar 02 '14 at 21:25
  • The main program reaches the last line, but when I run this from sbt, it does not return. – Daniel Cukier Mar 02 '14 at 21:34

0 Answers0