Created
April 23, 2013 19:40
-
-
Save vkobel/5446742 to your computer and use it in GitHub Desktop.
Example of how a simple system of actor and futures works in akka and scala
This file contains hidden or 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
package akkaActors | |
import akka.actor.{ Actor, ActorSystem, Props, PoisonPill } | |
import akka.pattern.ask // enable the use of ? or ask that return a future from an actor | |
import akka.util.Timeout | |
import scala.concurrent.Await | |
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global // import global execution context (implicit way) | |
class HelloActor extends Actor { | |
def receive = { | |
case "hello" => { | |
Thread.sleep(2000) | |
sender ! "hello to you too" | |
} | |
case _ => throw new Error("unexpected case") | |
} | |
} | |
object Main extends App { | |
implicit val system = ActorSystem("ActorSystem") | |
val helloActor = system.actorOf(Props[HelloActor], name = "helloActor") | |
implicit val timeout = Timeout(2100) | |
val future = helloActor ? "hello" | |
helloActor ! PoisonPill // properly shutdown the helloActor | |
println("execution...") | |
val res = Await.result(future, timeout.duration) | |
println(res) | |
system.shutdown // shutdown the akka actor system | |
} |
This file contains hidden or 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
package actors | |
import scala.actors.Actor | |
import scala.actors.Actor._ | |
class HelloActor extends Actor { | |
def act { | |
while (true) { | |
receive { | |
case "hello" => { | |
Thread.sleep(2000) | |
reply("hello to you too") | |
} | |
case "stop" => exit | |
case _ => throw new Error("unexpected case") | |
} | |
} | |
} | |
} | |
object ActorsTest extends App { | |
val actor = new HelloActor | |
actor.start | |
val future = actor !! "hello" | |
println("execution...") | |
println(future()) | |
actor ! "stop" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment