SlideShare a Scribd company logo
1 of 21
Akka and Actors
Usage patterns at Africa’s Talking
What is akka
“Akka is a toolkit and runtime for building highly concurrent, distributed, and resilient
message-driven applications” - LightBend
The actor model
An actor is a high level concurrency primitive that allows you to model concurrent
computations using entities that interact through message passing.
Why akka
Distributed
High performance
Self healing - let it crash model, fault recovery strategies
Asynchronous
Reactive manifesto - self healing resilient applications
The actor ...
An actor is a container for State, Behavior, a Mailbox, Child Actors and a Supervisor
Strategy.
All of this is encapsulated behind an Actor Reference
The actor model ...
1. Actors have an address so they can send and receive messages
2. These messages are stored in mailboxes (default is a FIFPO queue)
3. Actors can create other actors.
4. Actors have defined behaviour : functions which define the actions to be taken in
reaction to the message at that point in time
5. Actors don’t always map one-on-one to threads, several actors could belong to an
execution context on one thread.
6. An actor should not talk directly to another but interact through an Actor reference
- which points to the actor
The actor model ...
Actor Systems
Creating an Actor
The Actor trait defines only one abstract method, the above mentioned receive, which implements the behavior of the actor
import akka.actor.Actor
import akka.actor.Logging
class MyActor extends Actor {
val log = Logging(context.system, this)
def receive = {
case "test" => log.info("received test")
case _ => log.info("received unknown message")
}
}
The Actor API
1. self reference to the ActorRef of the actor
2. sender reference sender Actor of the last received message, typically used as
described in Reply to messages
3. supervisorStrategy user overridable definition the strategy to use for supervising
child actors
4. context exposes contextual information for the actor and the current message, such
as:
- factory methods to create child actors (actorOf)s
- system that the actor belongs to
Messages and Immutability
Messages can be any kind of object but have to be immutable. Scala can’t enforce
immutability (yet) so this has to be by convention. Primitives like String, Int, Boolean are
always immutable.
Recommended approach is to use Scala case classes which are immutable and work well
with pattern matching at the receiver side
case class Register(user: User)
val message = Register(user)
The actor model … design patterns
ask pattern - future; await or asynchronous
tell pattern - fire/ forget
Tell :Fire-forget
This is the preferred way of sending messages. No blocking waiting for a message. This
gives the best concurrency and scalability characteristics.
The target actor can use the sender function to reply this to reply to the original sender,
by using sender() ! replyMsg
actorRef ! message
Ask: Send-And-Receive-Future
? sends a message asynchronously and returns a Future representing a possible reply.
import akka.pattern.{ ask, pipe }
import system.dispatcher
// The ExecutionContext that will be used
final case class Result(x: Int, s: String, d: Double)
case object Request
implicit val timeout = Timeout(5 seconds) // needed for `?` below
val f: Future[Result] =
actorC ? Request.mapTo[Double]
f pipeTo actorD
The example demonstrates ask together with the pipeTo pattern on futures.
It is completely non-blocking and asynchronous: ask produces a Future then
pipeTo installs an onComplete-handler on the future to affect the submission of the
aggregated Result to another actor.
We reply with:
Sender ! replyMsg()
Note: There are performance implications of using ask since something needs to keep
track of when it times out and there needs to be something that bridges a Promise into
an ActorRef. Always prefer tell for performance, and only ask if you must
Futures
A Future is a data structure used to retrieve the result of some concurrent operation. This result can be accessed
synchronously (blocking) or asynchronously (non-blocking).
Using an Actor‘s ? method to send a message will return a Future. When using non-blocking it is better to use the
mapTo method to safely try to cast a Future to an expected type. On Complete callback allows you to define
behaviour when the future completes:
import scala.concurrent.Future
import akka.pattern.ask
val future: Future[String] = ask(actor, msg).mapTo[String]
future onComplete {
case Success => //do something
case Failure => //do something
Become/Unbecome
Akka supports hotswapping the Actor’s implementation at runtime. Invoke the become
method to implement the new message handler:
class HotSwapActor extends Actor {
import context._
def angry: Receive = {
case "foo" => sender() ! "I am already angry?"
case "bar" => become(happy)
}
def happy: Receive = {
case "bar" => sender() ! "I am already happy :-)"
case "foo" => become(angry)
}
def receive = {
case "foo" => become(angry)
case "bar" => become(happy)
}
Fault Handling
Each actor is the supervisor of its children, and as such each actor defines fault handling supervisor strategy.
Depending on the nature of the work to be supervised and the nature of the failure, the supervisor can resume,
restart, stop the actor or escalate the failure.
You can create your own or use a combined strategy as shown below:
import akka.actor.OneForOneStrategy
import akka.actor.SupervisorStrategy._
import scala.concurrent.duration._
override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException => Resume
case t =>
super.supervisorStrategy.decider.applyOrElse(t, (_: Any) => Escalate)
}
Actors at AT
Use of ask with futures(with handlers for success/failure) and pattern matching
Ask with mapTo/pipeTo very useful for object transformations where the upstream
expects a response in a certain format
Routing to load balance particularly busy actors
FSMs
Delayed restarts with Backoff Supervisor
Querying and Persisting
Test cases
Actors at AT...cont
Very Reliable and Scales Well
If extensively tested few outages
Bugs are usually the result of high efficiency
All the advantages of the JVM with the benefits of functional programming mixed in
Thanks for coming!

More Related Content

What's hot

Ap Power Point Chpt3 B
Ap Power Point Chpt3 BAp Power Point Chpt3 B
Ap Power Point Chpt3 Bdplunkett
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview QuestionsSumanth krishna
 
Presenter deck icenium hol
Presenter deck   icenium holPresenter deck   icenium hol
Presenter deck icenium holDhananjay Kumar
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8dplunkett
 
Chapter 4.2
Chapter 4.2Chapter 4.2
Chapter 4.2sotlsoc
 
Why you should use a testing framework
Why you should use a testing frameworkWhy you should use a testing framework
Why you should use a testing frameworkRichie Cotton
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Blue Elephant Consulting
 
Services Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJSServices Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJSSumanth krishna
 
: Look up the definition of the standard Comparable interface in the API docu...
: Look up the definition of the standard Comparable interface in the API docu...: Look up the definition of the standard Comparable interface in the API docu...
: Look up the definition of the standard Comparable interface in the API docu...hwbloom116
 
Intro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileIntro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileBlue Elephant Consulting
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2Todor Kolev
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style GuideJacky Lai
 
Looping statements
Looping statementsLooping statements
Looping statementsJaya Kumari
 

What's hot (20)

Operators in java
Operators in javaOperators in java
Operators in java
 
Ap Power Point Chpt3 B
Ap Power Point Chpt3 BAp Power Point Chpt3 B
Ap Power Point Chpt3 B
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview Questions
 
Akka - A Brief Intro
Akka - A Brief IntroAkka - A Brief Intro
Akka - A Brief Intro
 
07 flow control
07   flow control07   flow control
07 flow control
 
Presenter deck icenium hol
Presenter deck   icenium holPresenter deck   icenium hol
Presenter deck icenium hol
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8
 
Chapter 4.2
Chapter 4.2Chapter 4.2
Chapter 4.2
 
Why you should use a testing framework
Why you should use a testing frameworkWhy you should use a testing framework
Why you should use a testing framework
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2
 
Services Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJSServices Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJS
 
: Look up the definition of the standard Comparable interface in the API docu...
: Look up the definition of the standard Comparable interface in the API docu...: Look up the definition of the standard Comparable interface in the API docu...
: Look up the definition of the standard Comparable interface in the API docu...
 
Intro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileIntro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … While
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Java chapter 6
Java chapter 6Java chapter 6
Java chapter 6
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Looping statements
Looping statementsLooping statements
Looping statements
 

Similar to Nairobi JVM meetup : Introduction to akka

Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an IntroductionRoberto Casadei
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)Gagan Agrawal
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0Knoldus Inc.
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
Testing akka-actors
Testing akka-actorsTesting akka-actors
Testing akka-actorsKnoldus Inc.
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akkaWebdesign Factory
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 

Similar to Nairobi JVM meetup : Introduction to akka (20)

Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
Akka and futures
Akka and futuresAkka and futures
Akka and futures
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
 
Akka framework
Akka frameworkAkka framework
Akka framework
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Akka Testkit Patterns
Akka Testkit PatternsAkka Testkit Patterns
Akka Testkit Patterns
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Testing akka-actors
Testing akka-actorsTesting akka-actors
Testing akka-actors
 
Backday Xebia : Akka, the reactive toolkit
Backday Xebia : Akka, the reactive toolkitBackday Xebia : Akka, the reactive toolkit
Backday Xebia : Akka, the reactive toolkit
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akka
 
G pars
G parsG pars
G pars
 
Core java
Core javaCore java
Core java
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 

Recently uploaded

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 

Recently uploaded (20)

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 

Nairobi JVM meetup : Introduction to akka

  • 1. Akka and Actors Usage patterns at Africa’s Talking
  • 2. What is akka “Akka is a toolkit and runtime for building highly concurrent, distributed, and resilient message-driven applications” - LightBend
  • 3. The actor model An actor is a high level concurrency primitive that allows you to model concurrent computations using entities that interact through message passing.
  • 4. Why akka Distributed High performance Self healing - let it crash model, fault recovery strategies Asynchronous Reactive manifesto - self healing resilient applications
  • 5. The actor ... An actor is a container for State, Behavior, a Mailbox, Child Actors and a Supervisor Strategy. All of this is encapsulated behind an Actor Reference
  • 6. The actor model ... 1. Actors have an address so they can send and receive messages 2. These messages are stored in mailboxes (default is a FIFPO queue) 3. Actors can create other actors. 4. Actors have defined behaviour : functions which define the actions to be taken in reaction to the message at that point in time 5. Actors don’t always map one-on-one to threads, several actors could belong to an execution context on one thread. 6. An actor should not talk directly to another but interact through an Actor reference - which points to the actor
  • 9. Creating an Actor The Actor trait defines only one abstract method, the above mentioned receive, which implements the behavior of the actor import akka.actor.Actor import akka.actor.Logging class MyActor extends Actor { val log = Logging(context.system, this) def receive = { case "test" => log.info("received test") case _ => log.info("received unknown message") } }
  • 10. The Actor API 1. self reference to the ActorRef of the actor 2. sender reference sender Actor of the last received message, typically used as described in Reply to messages 3. supervisorStrategy user overridable definition the strategy to use for supervising child actors 4. context exposes contextual information for the actor and the current message, such as: - factory methods to create child actors (actorOf)s - system that the actor belongs to
  • 11. Messages and Immutability Messages can be any kind of object but have to be immutable. Scala can’t enforce immutability (yet) so this has to be by convention. Primitives like String, Int, Boolean are always immutable. Recommended approach is to use Scala case classes which are immutable and work well with pattern matching at the receiver side case class Register(user: User) val message = Register(user)
  • 12. The actor model … design patterns ask pattern - future; await or asynchronous tell pattern - fire/ forget
  • 13. Tell :Fire-forget This is the preferred way of sending messages. No blocking waiting for a message. This gives the best concurrency and scalability characteristics. The target actor can use the sender function to reply this to reply to the original sender, by using sender() ! replyMsg actorRef ! message
  • 14. Ask: Send-And-Receive-Future ? sends a message asynchronously and returns a Future representing a possible reply. import akka.pattern.{ ask, pipe } import system.dispatcher // The ExecutionContext that will be used final case class Result(x: Int, s: String, d: Double) case object Request implicit val timeout = Timeout(5 seconds) // needed for `?` below val f: Future[Result] = actorC ? Request.mapTo[Double] f pipeTo actorD
  • 15. The example demonstrates ask together with the pipeTo pattern on futures. It is completely non-blocking and asynchronous: ask produces a Future then pipeTo installs an onComplete-handler on the future to affect the submission of the aggregated Result to another actor. We reply with: Sender ! replyMsg() Note: There are performance implications of using ask since something needs to keep track of when it times out and there needs to be something that bridges a Promise into an ActorRef. Always prefer tell for performance, and only ask if you must
  • 16. Futures A Future is a data structure used to retrieve the result of some concurrent operation. This result can be accessed synchronously (blocking) or asynchronously (non-blocking). Using an Actor‘s ? method to send a message will return a Future. When using non-blocking it is better to use the mapTo method to safely try to cast a Future to an expected type. On Complete callback allows you to define behaviour when the future completes: import scala.concurrent.Future import akka.pattern.ask val future: Future[String] = ask(actor, msg).mapTo[String] future onComplete { case Success => //do something case Failure => //do something
  • 17. Become/Unbecome Akka supports hotswapping the Actor’s implementation at runtime. Invoke the become method to implement the new message handler: class HotSwapActor extends Actor { import context._ def angry: Receive = { case "foo" => sender() ! "I am already angry?" case "bar" => become(happy) } def happy: Receive = { case "bar" => sender() ! "I am already happy :-)" case "foo" => become(angry) } def receive = { case "foo" => become(angry) case "bar" => become(happy) }
  • 18. Fault Handling Each actor is the supervisor of its children, and as such each actor defines fault handling supervisor strategy. Depending on the nature of the work to be supervised and the nature of the failure, the supervisor can resume, restart, stop the actor or escalate the failure. You can create your own or use a combined strategy as shown below: import akka.actor.OneForOneStrategy import akka.actor.SupervisorStrategy._ import scala.concurrent.duration._ override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case t => super.supervisorStrategy.decider.applyOrElse(t, (_: Any) => Escalate) }
  • 19. Actors at AT Use of ask with futures(with handlers for success/failure) and pattern matching Ask with mapTo/pipeTo very useful for object transformations where the upstream expects a response in a certain format Routing to load balance particularly busy actors FSMs Delayed restarts with Backoff Supervisor Querying and Persisting Test cases
  • 20. Actors at AT...cont Very Reliable and Scales Well If extensively tested few outages Bugs are usually the result of high efficiency All the advantages of the JVM with the benefits of functional programming mixed in

Editor's Notes

  1. Escalate is used if the defined strategy doesn’t cover the exception that was thrown. When the supervisor strategy is not defined for an actor the following exceptions are handled by default: • ActorInitializationException will stop the failing child actor • ActorKilledException will stop the failing child actor • DeathPactException will stop the failing child actor • Exception will restart the failing child actor • Other types of Throwable will be escalated to parent actor If the exception escalate all the way up to the root guardian it will handle it in the same way as the default strategy defined above.
  2. mplements the so-called exponen- tial backoff supervision strategy, starting a child actor again when it fails, each time with a growing time delay between restarts. This pattern is useful when the started actor fails 1 because some external resource is not available,