Skip to content

Instantly share code, notes, and snippets.

@sgireddy
Created January 7, 2017 20:45
Show Gist options
  • Select an option

  • Save sgireddy/9fe37ab7ff79ad1dd1de219bca0d2eb8 to your computer and use it in GitHub Desktop.

Select an option

Save sgireddy/9fe37ab7ff79ad1dd1de219bca0d2eb8 to your computer and use it in GitHub Desktop.
A simple word count example to explain Akka Actor System
/**
* Created by sri on 1/6/17.
*/
object domain {
case class Start()
case class DoWork(line: String)
case class Done(wordsInLine: Integer)
}
import akka.actor.{Actor, ActorRef, Props}
import domain._
import scala.io.Source
/**
* Created by sri on 1/6/17.
*/
case class Master(fileName: String) extends Actor {
var totalLines = 0
var totalWords = 0
var linesSoFar = 0
private var senderRef: Option[ActorRef] = None
def receive={
case Start => {
senderRef = Some(sender)
Source.fromFile(fileName).getLines().foreach( line => {
context.actorOf(Props[Slave]) ! DoWork(line)
totalLines+=1
})
}
case Done(cnt) =>{
totalWords += cnt
linesSoFar += 1
if(linesSoFar == totalLines) {
senderRef.map(_ ! totalWords) //Don't use sender, we don't want to send to the Slave......
}
}
case _ => "What Do I do?"
}
}
import akka.actor.Actor
import domain._
/**
* Created by sri on 1/6/17.
*/
case class Slave() extends Actor {
def receive = {
case DoWork(line) => {
val cnt = line.split(" ").length
sender ! Done(cnt)
}
case _ => println("Unknown Work!")
}
}
import akka.actor.{ActorSystem, Props}
import akka.dispatch.ExecutionContexts._
import akka.pattern.ask
import akka.util.Timeout
import domain.Start
import scala.concurrent.duration._
object WordCounter extends App {
implicit val gc = global
implicit val timeout = Timeout(25 seconds)
val system = ActorSystem("MyWordCounter")
val master = system.actorOf(Props(Master("/home/sri/rdp.sh")))
val future = master ? Start
future.map { res =>
println(res)
system.terminate()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment