Last active
March 31, 2017 08:47
-
-
Save diogoaurelio/871a9e06b77b297d3a26ca7b42d35379 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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