Akka and futures

28
Akka Actors And Futures Meetu Maltiar Principal Consultant Email: [email protected] Twitter:@meetumaltiar

description

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

Transcript of Akka and futures

Page 1: Akka and futures

Akka Actors And Futures

Meetu MaltiarPrincipal Consultant

Email: [email protected]:@meetumaltiar

Page 2: Akka and futures

Akka 2.0

Akka name comes from Sami mythology is actually name of a goddess of wisdom and beauty.

Akka incidentally means sister in Telugu!!

Page 3: Akka and futures

The Problem

It is way too hard to build

=> correct highly concurrent systems

=> truly scalable systems

=> self-healing, fault-tolerant systems

Page 4: Akka and futures

What is Akka?Right abstraction with actors for concurrent, fault-tolerant and scalable applications

For Fault-Tolerance uses “let it crash” model

Abstraction for transparent distribution for load

Page 5: Akka and futures

Introducing Actors

Actor is an entity encapsulating behavior, state and a mailbox to receive messages

For a message received by Actor a thread is allocated to it

Then Actors behavior is applied to the message and potentially some state is changed or messages is passed to other Actors

Page 6: Akka and futures

Introducing Actors..

There is elasticity between message processing and addition of new messages. New messages can be added while actor execution is happening.

When processing of messages is completed thread is deallocated from the actor. It can be reallocated a thread at a later time

Page 7: Akka and futures
Page 8: Akka and futures
Page 9: Akka and futures
Page 10: Akka and futures
Page 11: Akka and futures

Create Application

import akka.actor.ActorSystem

val system = ActorSystem("firstApp")

Page 12: Akka and futures

My First Actorimport akka.actor.{ Actor, Props }

class MyFirstActor extends Actor { def receive = { case msg => println("Hello!!") }}

Page 13: Akka and futures

Create Actors

MyFirstActor is an ActorRefCreate a top level actor

import akka.actor.{ ActorSystem, Props }

val system = ActorSystem("firstApp")val myFirstActor = system.actorOf(Props[MyFirstActor])

Page 14: Akka and futures

Stop Actors

Also stops all actors in hierarchy

system stop myFirstActor

Page 15: Akka and futures

Send: !

fire-forget

myFirstActor ! “Hello”

Page 16: Akka and futures

Ask: ?

Returns a Future[Any]

import akka.pattern.ask

implicit val timeout = Timeout(50000 milliseconds)

val future = myActor ? "hello"

Await.result(future, timeout.duration).asInstanceOf[Int]

Page 17: Akka and futures

Replyimport akka.actor.Actor

class LongWorkingActor extends Actor { def receive = { case number: Int => sender ! (“Hi I received ” + number) }}

Page 18: Akka and futures

Routers

RoundRobin

Random

SmallestMailBox

BroadCast

ScatterGatherFirstCompleted

Page 19: Akka and futures

Routers...

val router = system.actorOf(Props[RouterWorkerActor].withRouter(RoundRobinRouter(nrOfInstances = 5)))

Page 20: Akka and futures

Actor Path

val actorRef = system.actorFor("akka://actorPathApp/user/parent/child")

val parent = context.actorFor("..")

val sibling = context.actorFor("../sibling")

val refPath = actorRef.path

Page 21: Akka and futures

Akka FuturesA Future is a data structure

Used to retrieve of some concurrent operation

This operation is performed by an Actor or a dispatcher directly

The result can be accessed synchronously or asynchronously

Page 22: Akka and futures

Execution Context

Futures need ExecutionContext to execute callback and operations

If we have ActorSystem in scope Future will use default dispatcher as ExecutionContext

We can use factory methods provided by ExecutionContext companion object to wrap Executors and ExecutorServices

Page 23: Akka and futures

Use With Actors

There are two ways to get a reply from an Actor. First one is (myActor ! Msg)

The second way is through a Future. Using Actors “?” method will return a Future

The simplest way to use Await method call, though not recommended as the thread blocks till result is obtained.

Page 24: Akka and futures

Future With Akka andAwait

import akka.actor._import akka.pattern.askimport akka.util.duration._import akka.util.Timeoutimport akka.dispatch.Await

object 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)}

Page 25: Akka and futures

Use Futures Directly

import akka.dispatch._import akka.util.duration._import akka.actor.ActorSystem

object 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)}

Page 26: Akka and futures

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)}

Page 27: Akka and futures

Code Samples

https://github.com/meetumaltiar/AkkaKnolX

Page 28: Akka and futures

References

Viktor Klang talk on Akka 2.0 at NE Scala symposium

Akka website akka.io