Skip to content

Instantly share code, notes, and snippets.

@patriknw
Created May 21, 2012 19:07
Show Gist options
  • Save patriknw/2764019 to your computer and use it in GitHub Desktop.
Save patriknw/2764019 to your computer and use it in GitHub Desktop.
Mailinglist question about watching routees for termination
package question
import java.io.IOException
import scala.util.Random
import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.OneForOneStrategy
import akka.actor.Props
import akka.actor.SupervisorStrategy.Restart
import akka.actor.Terminated
import akka.dispatch.Await
import akka.pattern.ask
import akka.routing.CurrentRoutees
import akka.routing.RoundRobinRouter
import akka.routing.RouterRoutees
import akka.util.Timeout
import akka.util.duration._
object RouterApp extends App {
val system = ActorSystem()
val master = system.actorOf(Props[Master], "master")
implicit val timeout = Timeout(10 seconds)
try
println(Await.result(master ? "start", timeout.duration))
catch {
case e ⇒ println(e.getMessage)
} finally {
system.shutdown()
}
}
class Master extends Actor {
var results = Map[Int, Int]()
var replyTo: ActorRef = _
val router = context.actorOf(Props(new Worker).
withRouter(RoundRobinRouter(5,
supervisorStrategy = OneForOneStrategy(
maxNrOfRetries = 2) {
case _: IOException ⇒ Restart
})), name = "router")
router ! CurrentRoutees
def receive = {
case RouterRoutees(routees) ⇒
routees foreach context.watch
case "start" ⇒
replyTo = sender
for (id ← 1 to 10) router ! (id, "22")
case (id: Int, result: Int) ⇒
results += (id -> result)
if (results.size == 10)
replyTo ! results.values.sum
case Terminated(actor) ⇒
replyTo ! -1
context.stop(self)
}
}
class Worker extends Actor {
def receive = {
case (id, s: String) if Random.nextInt(4) == 0 ⇒
throw new IOException("failed")
case (id, s: String) ⇒
sender ! (id, s.toInt)
}
override def preRestart(
reason: Throwable, message: Option[Any]) {
// retry
message foreach { self forward _ }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment