Skip to content

Instantly share code, notes, and snippets.

@diogoaurelio
Last active March 31, 2017 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diogoaurelio/871a9e06b77b297d3a26ca7b42d35379 to your computer and use it in GitHub Desktop.
Save diogoaurelio/871a9e06b77b297d3a26ca7b42d35379 to your computer and use it in GitHub Desktop.
import java.util.concurrent.TimeUnit
import akka.actor.{Actor, ActorSystem, Props}
import scala.concurrent.Await
import scala.concurrent.duration.Duration
/**
* Simple Actor
*/
object actorDemo extends App {
// Initialize an Actor System
val system = ActorSystem("DemoActors")
// In case you're wondering, lyrics from The Flying Eyes, Bad Blood
val lyrics = List("Please suck my blood", "Suck my blood clean",
"Please purge the venom", "Living inside me, inside of me", "Cuz I'm feeling sick",
"I'm feeling so crazy", "Since she crawled away", "I've been starving now",
"Starving now", "Please wake me up", "Cuz I'm tired of sleep", "But some of these days",
"I'd rather sit and dream", "Cuz I'm feeling strange", "I'm feeling so crazy",
"Since she crawled away", "I've been starving now", "Starving now")
// Create one instance of each actor (WordCountActor and UpperCaseActor
val wordCountActor = system.actorOf(Props[WordCountActor], name = "WordCountDemoActor")
val upperCaseActor = system.actorOf(Props[UpperCaseActor], name = "UpperCaseDemoActor")
println("============ Initializing demo =================")
lyrics foreach { sentence =>
// Send actors a message via " ! " method
// Note that these will be processed asynchronously
wordCountActor ! Work(sentence)
upperCaseActor ! Work(sentence)
}
Thread.sleep(2)
system.shutdown()
}
case class Work(text: String)
class WordCountActor extends Actor {
override def receive: Receive = {
case Work(text) => processText(text)
}
def processText(text: String): Unit = {
val len = text.split("\\s+").length
println(s"${self.path.toStringWithoutAddress} received sentence: '${text}' \nSetence word count=${len}")
}
}
class UpperCaseActor extends Actor {
override def receive: Receive = {
case Work(text) => processText(text)
}
def processText(text: String): Unit = {
println(s"${self.path.toStringWithoutAddress} Received sentence '${text}' \nSentence capitalized: ${text.toUpperCase}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment