Akka and futures


Published on

Presented in Knolx session at Knoldus. This presentation focuses on Akka 2.0 with special emphasis on Futures

  • Be the first to comment

Akka and futures

  1. 1. Akka Actors And Futures Meetu Maltiar Principal Consultant Email: meetu@knoldus.com Twitter:@meetumaltiar
  2. 2. Akka 2.0Akka name comes from Sami mythology is actually name of a goddess of wisdom and beauty. Akka incidentally means sister in Telugu!!
  3. 3. The ProblemIt is way too hard to build => correct highly concurrent systems => truly scalable systems => self-healing, fault-tolerant systems
  4. 4. What is Akka?Right abstraction with actors for concurrent, fault-tolerantand scalable applicationsFor Fault-Tolerance uses “let it crash” modelAbstraction for transparent distribution for load
  5. 5. Introducing ActorsActor is an entity encapsulating behavior, state and amailbox to receive messagesFor a message received by Actor a thread is allocated to itThen Actors behavior is applied to the message andpotentially some state is changed or messages is passed toother Actors
  6. 6. Introducing Actors..There is elasticity between message processing and additionof new messages. New messages can be added while actorexecution is happening.When processing of messages is completed thread isdeallocated from the actor. It can be reallocated a thread at alater time
  7. 7. Create Applicationimport akka.actor.ActorSystemval system =ActorSystem("firstApp")
  8. 8. My First Actorimport akka.actor.{ Actor, Props }class MyFirstActor extends Actor { def receive = { case msg => println("Hello!!") }}
  9. 9. Create Actorsimport akka.actor.{ ActorSystem, Props }val system = ActorSystem("firstApp")val myFirstActor =system.actorOf(Props[MyFirstActor]) MyFirstActor is an ActorRef Create a top level actor
  10. 10. Stop Actorssystem stop myFirstActorAlso stops all actors in hierarchy
  11. 11. Send: !myFirstActor ! “Hello” fire-forget
  12. 12. Ask: ?import akka.pattern.askimplicit val timeout = Timeout(50000 milliseconds)val future = myActor ? "hello"Await.result(future, timeout.duration).asInstanceOf[Int] Returns a Future[Any]
  13. 13. Replyimport akka.actor.Actorclass LongWorkingActor extends Actor { def receive = { case number: Int => sender ! (“Hi I received ” + number) }}
  14. 14. RoutersRoundRobinRandomSmallestMailBoxBroadCastScatterGatherFirstCompleted
  15. 15. Routers...val router =system.actorOf(Props[RouterWorkerActor].withRouter(RoundRobinRouter(nrOfInstances = 5)))
  16. 16. Actor Pathval actorRef =system.actorFor("akka://actorPathApp/user/parent/child")val parent = context.actorFor("..")val sibling = context.actorFor("../sibling")val refPath = actorRef.path
  17. 17. Akka FuturesA Future is a data structureUsed to retrieve of some concurrentoperationThis operation is performed by an Actor or adispatcher directlyThe result can be accessed synchronously orasynchronously
  18. 18. Execution ContextFutures need ExecutionContext to executecallback and operationsIf we have ActorSystem in scope Future willuse default dispatcher as ExecutionContextWe can use factory methods provided byExecutionContext companion object to wrapExecutors and ExecutorServices
  19. 19. Use With ActorsThere are two ways to get a reply from anActor. First one is (myActor ! Msg)The second way is through a Future. UsingActors “?” method will return a FutureThe simplest way to use Await method call,though not recommended as the thread blockstill result is obtained.
  20. 20. Future With Akka andAwaitimport akka.actor._import akka.pattern.askimport akka.util.duration._import akka.util.Timeoutimport akka.dispatch.Awaitobject FutureWithAwaitApp extends App { implicit val timeout = Timeout(50000 milliseconds) val system = ActorSystem("future") val echoActor = system.actorOf(Props[EchoActor]) val future = echoActor ? "Hello World" val result = Await.result(future,timeout.duration).asInstanceOf[String] println(result)}
  21. 21. Use Futures Directlyimport akka.dispatch._import akka.util.duration._import akka.actor.ActorSystemobject MonadicFutureApplication extends App { implicit val system = ActorSystem("future") val f1 = Future { "Hello" + "World" } val f2 = f1 map { x => x.length } val result = Await.result(f2, 1 second) println(result)}
  22. 22. Composing Futuresobject MultiMonadicFutureApplication extends App { implicit val system = ActorSystem("future") val f1 = Future { "Hello" + "World" } val f2 = Future { 3 } val f3 = f1 flatMap { x => f2 map { y => x.length * y } } val result = Await.result(f3, 1 second)}
  23. 23. Code Sampleshttps://github.com/meetumaltiar/AkkaKnolX
  24. 24. ReferencesViktor Klang talk on Akka 2.0 at NE Scala symposiumAkka website akka.io