Introducing Akka
-
Upload
meetu-maltiar -
Category
Engineering
-
view
995 -
download
7
description
Transcript of Introducing Akka
![Page 1: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/1.jpg)
Introducing Akka
Meetu Maltiar Cisco
blog: meetumaltiar.wordpress.com twitter: @meetumaltiar
28th June 2014
![Page 2: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/2.jpg)
AgendaHistory of Akka
Scala basics
The use case of Akka
Akka Actors
Akka Supervision
![Page 3: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/3.jpg)
HistoryPhilipp Haller worked on Actor model and released it in Scala 2.1.7 in July 2006
Jonas Boner created Akka to bring highly concurrent, event driven to JVM
Inspired by Erlang Actors, Jonas Boner began working on Akka early 2009
Jonas Boner as part of Scalable Solutions releases Akka version 0.5 in January 2010
Akka is now part of Typesafe Platform together with Play framework and Scala language
![Page 4: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/4.jpg)
Akka Who Uses It
![Page 5: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/5.jpg)
Scala BasicsScala is a JVM based strongly typed language
Scala is hybrid: Functional as well as Object-Oriented
Scala is compatible with Java
Scala has support for currying, pattern matching, ADT’s, lazy evaluation, tail recursion etc
Scala is compiled to Java byte-codes and run on Java Virtual Machine
![Page 6: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/6.jpg)
Scala Compared To JavaScala adds Scala removes
pure object system static members
operator overloading primitive types
closures break and continue
mixin composition with traits special treatment of interfaces
existential types wildcards
abstract types raw types
pattern matching enums
![Page 7: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/7.jpg)
Scala Cheat Sheet(1) definitions
Scala method definitions !def fun(x: Int) = { result } !def fun = result !Scala variable definitions !var x: Int = expression val x: String = expression
Java method definitions !Int fun(int x) { return result } !(no parameterless methods) !java variable definitions !Int x = expression final String x = expression
![Page 8: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/8.jpg)
Scala Cheat Sheet(2) definitionsScala class and object !class Sample(x: Int, p: Int) { def instMeth(y: Int): Int = x + y } !object Sample { def staticMeth(x: Int, y: Int): Int = x * y } !!!!!!!!!
Java class !class Sample { private final int x; public final int p; ! Sample(int x, int p) { this.x = x; this.p = p; } ! int instMeth(int y) { return x + y; } ! static int staticMeth(int x, int y) { return x *y; } }
![Page 9: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/9.jpg)
Scala: Pattern MatchingAll that is required to add a case keyword to each class that is to be pattern matchable !Pattern match also returns a value !Similar to switch except that Scala compares objects as expressions. Only one matcher is executed at a time. !case class Employee(name: String) val employee = Employee(“john”) employee match { case Employee(“john”) => “Hello John!” case _ => “Hello there!” } !res0: String = Hello John
![Page 10: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/10.jpg)
AkkaThe name comes from a goddess in Sami mythology that
represented all wisdom and beauty in the world
It is also the name of a beautiful mountain in Laponia in north part of Sweden
Incidentally in India it means sister in Telugu!!
![Page 11: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/11.jpg)
The ProblemIt is way to hard to build
=> correct highly concurrent systems
=> Truly scalable systems
=> self-healing, fault-tolerant systems
![Page 12: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/12.jpg)
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 of load
We can Scale In and Scale Out
![Page 13: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/13.jpg)
Right AbstractionNever think in terms of shared state, state visibility, threads, locks, concurrent collections, thread notification etc
Low level concurrency becomes Simple Workflow - we only think in terms of message flows in system
We get high CPU utilisation, low latency, high throughput and scalability - for free as part of this model
Proven and superior model for detecting and recovering from errors
![Page 14: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/14.jpg)
Actor ModelActor Model (1973): Carl Hewitt’s definition !The fundamental unit of computation that embodies: - Processing - Storage - Communication !Three Axioms - Create new Actors - Send messages to Actor it knows - Designate how it should handle the next message it receives
![Page 15: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/15.jpg)
Introducing ActorsActor is an entity encapsulating behaviour, state and a mailbox to receive messages
For a message received by Actor a thread is allocated to it
Then behaviour is applied to the message and potentially some state is changed or messages are passed to other Actors
![Page 16: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/16.jpg)
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; the thread is deallocated from the Actor. It can again be reallocated a thread at a later time.
![Page 17: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/17.jpg)
Mailbox
Actor having behaviour, state and a mailbox Messages are in mailbox No thread is allocated to the Actor
![Page 18: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/18.jpg)
Thread is allocated to the Actor It is now ready to read message and apply behaviour
Mailbox
![Page 19: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/19.jpg)
Thread is allocated to the Actor It has read message and is applying behaviour
Mailbox
![Page 20: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/20.jpg)
Mailbox
Actor has handled message Thread is deallocated It will be allocated a thread later
![Page 21: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/21.jpg)
Create Actor SystemActorSystem is a heavy-weight structure that will allocate 1…n threads. So,create one per logical application !Top level actors are created from an ActorSystem !This is so because first Actor is the child from ActorSystem. If we create another Actor from this first Actor: then second Actor will be child of the first Actor !We therefore get a tree like structure and hence get automatic supervision !val system = ActorSystem("myfirstApp")
![Page 22: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/22.jpg)
My First Actor
import akka.actor._!class MyFirstActor extends Actor { def receive = { case msg: String => println(msg) case _ => println("default") }}
you extend an Actor !receive method reads the message from mailbox !receive is a partially applied function !pattern match is applied on the message
![Page 23: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/23.jpg)
Create Actor
package com.meetu.akka!import akka.actor._!object HelloWorldAkkaApplication extends App { val system = ActorSystem("myfirstApp") val myFirstActor: ActorRef = system.actorOf(Props[MyFirstActor]) ……..}
Create an Actor System !create actor from Actor System using actorOf method !the actorOf method returns an ActorRef instead of Actor class type
![Page 24: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/24.jpg)
Create Actor
when actorOf is called path is reserved !A random UID is assigned to incarnation !Actor instance is created !preStart is called on instance
![Page 25: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/25.jpg)
Send Message
package com.meetu.akka!import akka.actor._!object HelloWorldAkkaApplication extends App { val system = ActorSystem("myfirstApp") val myFirstActor: ActorRef = system.actorOf(Props[MyFirstActor]) myFirstActor ! "Hello World" myFirstActor.!("Hello World")}
Scala version has a method named “!” !This is asynchronous thread of execution continues after sending !It accepts Any as a parameter !In Scala we can skip a dot with a space: So it feels natural to use
![Page 26: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/26.jpg)
Ask Pattern
package com.meetu.akka!import akka.actor._import akka.pattern.askimport akka.util.Timeoutimport scala.concurrent.duration._import scala.concurrent.Awaitimport scala.concurrent.Future!object AskPatternApp extends App { implicit val timeout = Timeout(500 millis) val system = ActorSystem("BlockingApp") val echoActor = system.actorOf(Props[EchoActor])! val future: Future[Any] = echoActor ? "Hello" val message = Await.result(future, timeout.duration).asInstanceOf[String]! println(message)}!class EchoActor extends Actor { def receive = { case msg => sender ! msg }}
Ask pattern is blocking !Thread of execution waits till response is reached
![Page 27: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/27.jpg)
Reply From Actor
import akka.actor.Actor!class LongWorkingActor extends Actor { def receive = { case number: Int => sender ! ("Hi I received the " + number) }}
Each Actor has been provided default sender !Use “!” method to send back the message
![Page 28: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/28.jpg)
RoutersRoundRobin !Random !SmallestMailBox !Broadcast !ScatterGatherFirstCompleted
![Page 29: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/29.jpg)
Round Robin Router
import akka.actor._import akka.routing.RoundRobinPoolimport akka.routing.Broadcast!object RouterApp extends App { val system = ActorSystem("routerApp") val router = system.actorOf(RoundRobinPool(5).props(Props[RouterWorkerActor]), "workers") router ! Broadcast("Hello")}!class RouterWorkerActor extends Actor { def receive = { case msg => println(s"Message: $msg received in ${self.path}") }}
A router sits on top of routees !When messages are sent to Router, Routees get messages in Round Robin
![Page 30: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/30.jpg)
Failure: Typical ScenarioThere is a single thread of control !If this Thread goes in failure we are doomed !We therefore do explicit error handling on this thread !Worse error do not propagate between threads. There is no way of knowing that something failed !We therefore do defensive programming with: • Error handling tangled with business logic • Scattered all over code base !We can do better than this
![Page 31: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/31.jpg)
Supervision
Supervise means manage another Actor failures !Error handling in Actors is handled by letting Actors monitor (supervise) each other of failure !This means if Actor crashes a notification is sent to its supervisor (an Actor), who can react to failure !This provides clean separation of processing and error handling
![Page 32: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/32.jpg)
…Let’s take a standard OO application
![Page 33: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/33.jpg)
Which components have critically important state
and Explicit error handling
![Page 34: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/34.jpg)
![Page 35: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/35.jpg)
![Page 36: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/36.jpg)
![Page 37: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/37.jpg)
![Page 38: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/38.jpg)
![Page 39: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/39.jpg)
Supervise ActorEvery Actor exists in a Tree topology. Its parent provide automatic supervision !Every Actor has a default Supervision strategy, which is usually sufficient !supervision strategy can be overridden !We have either One for One strategy. Here only the Actor that crashed is handled. !Other one is All For One strategy. Here all children are restarted
![Page 40: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/40.jpg)
Supervision Actorclass Supervisor extends Actor { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: IllegalArgumentException => Stop case _: Exception => Escalate }! def receive = { case p: Props => sender ! context.actorOf(p) }}
![Page 41: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/41.jpg)
Supervision: Child Actorclass Child extends Actor { var state = 0 def receive = { case ex: Exception => throw ex case x: Int => state = x case "get" => sender ! state }}
![Page 42: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/42.jpg)
Supervision Applicationobject SupervisionExampleApp extends App { implicit val timeout = Timeout(50000 milliseconds) val system = ActorSystem("supervisionExample") val supervisor = system.actorOf(Props[Supervisor], "supervisor") val future = supervisor ? Props[Child] val child = Await.result(future, timeout.duration).asInstanceOf[ActorRef] child ! 42 println("Normal response " + Await.result(child ? "get", timeout.duration).asInstanceOf[Int]) child ! new ArithmeticException println("Arithmetic Exception response " + Await.result(child ? "get", timeout.duration).asInstanceOf[Int]) child ! new NullPointerException println("Null Pointer response " + Await.result(child ? "get", timeout.duration).asInstanceOf[Int])}
![Page 43: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/43.jpg)
Running Supervision Application
![Page 44: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/44.jpg)
Learning Resources
Code examples at Githubhttps://github.com/meetumaltiar/AkkaQuickStart!Akka Documentationhttp://akka.io/docs/!Scala Documentationhttp://www.scala-lang.org/documentation/
![Page 45: Introducing Akka](https://reader031.fdocuments.us/reader031/viewer/2022012314/5549aa89b4c9050c708b56eb/html5/thumbnails/45.jpg)
Thank You!!