SlideShare a Scribd company logo
Introducing Akka
Meetu Maltiar
Cisco
blog: meetumaltiar.wordpress.com
twitter: @meetumaltiar
28th June 2014
Agenda
History of Akka
Scala basics
The use case of Akka
Akka Actors
Akka Supervision
History
Philipp 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
Akka Who Uses It
Scala Basics
Scala 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
Scala Compared To Java
Scala 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
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
Scala Cheat Sheet(2) definitions
Scala 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;
}
}
Scala: Pattern Matching
All 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
Akka
The 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!!
The Problem
It is way to hard to build
=> correct highly concurrent systems
=> Truly scalable systems
=> self-healing, fault-tolerant systems
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
Right Abstraction
Never 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
Actor Model
Actor 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
Introducing Actors
Actor 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
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.
Mailbox
Actor having behaviour, state and a mailbox
Messages are in mailbox
No thread is allocated to the Actor
Thread is allocated to the Actor
It is now ready to read message and apply behaviour
Mailbox
Thread is allocated to the Actor
It has read message and is applying behaviour
Mailbox
Mailbox
Actor has handled message
Thread is deallocated
It will be allocated a thread later
Create Actor System
ActorSystem 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")
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
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
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
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
Ask Pattern
package com.meetu.akka	
!
import akka.actor._	
import akka.pattern.ask	
import akka.util.Timeout	
import scala.concurrent.duration._	
import scala.concurrent.Await	
import 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
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
Routers
RoundRobin
!
Random
!
SmallestMailBox
!
Broadcast
!
ScatterGatherFirstCompleted
Round Robin Router
import akka.actor._	
import akka.routing.RoundRobinPool	
import 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
Failure: Typical Scenario
There 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
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
…Let’s take a
standard OO
application
Which components have
critically important state
and
Explicit error handling
Supervise Actor
Every 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
Supervision Actor
class 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)	
}	
}
Supervision: Child Actor
class Child extends Actor {	
var state = 0	
def receive = {	
case ex: Exception => throw ex	
case x: Int => state = x	
case "get" => sender ! state	
}	
}
Supervision Application
object 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])	
}
Running Supervision Application
Learning
Resources
Code examples at Github	
https://github.com/meetumaltiar/AkkaQuickStart	
!
Akka Documentation	
http://akka.io/docs/	
!
Scala Documentation	
http://www.scala-lang.org/documentation/
Thank You!!

More Related Content

What's hot

Scala Intro
Scala IntroScala Intro
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
Scala basic
Scala basicScala basic
Scala basic
Nguyen Tuan
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
Urs Peter
 
Scala test
Scala testScala test
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
Mahmoud Ali
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
Amuhinda Hungai
 
All about scala
All about scalaAll about scala
All about scala
Yardena Meymann
 

What's hot (19)

Scala Intro
Scala IntroScala Intro
Scala Intro
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Scala basic
Scala basicScala basic
Scala basic
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
Scala test
Scala testScala test
Scala test
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
All about scala
All about scalaAll about scala
All about scala
 

Similar to Introducing Akka

Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
Knoldus Inc.
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akka
Webdesign Factory
 
Akka and futures
Akka and futuresAkka and futures
Akka and futures
Knoldus Inc.
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
AD_
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
Meetu Maltiar
 
Akka knolx
Akka knolxAkka knolx
Akka knolx
Knoldus Inc.
 
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
Knoldus Inc.
 
Testing akka-actors
Testing akka-actorsTesting akka-actors
Testing akka-actors
Knoldus Inc.
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter
 
Build Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuBuild Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and Heroku
Salesforce Developers
 
Building reactive systems with Akka
Building reactive systems with AkkaBuilding reactive systems with Akka
Building reactive systems with Akka
Kristof Jozsa
 
Akka framework
Akka frameworkAkka framework
Akka framework
mitesh_sharma
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"
Anna Shymchenko
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
Roberto Casadei
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
Yung-Lin Ho
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
Yardena Meymann
 
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Networks and Types - the Future of Akka @ ScalaDays NYC 2018Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Konrad Malawski
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
Maciej Matyjas
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
Skills Matter
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
Gal Marder
 

Similar to Introducing Akka (20)

Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akka
 
Akka and futures
Akka and futuresAkka and futures
Akka and futures
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
 
Akka knolx
Akka knolxAkka knolx
Akka knolx
 
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
 
Testing akka-actors
Testing akka-actorsTesting akka-actors
Testing akka-actors
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Build Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and HerokuBuild Cloud Applications with Akka and Heroku
Build Cloud Applications with Akka and Heroku
 
Building reactive systems with Akka
Building reactive systems with AkkaBuilding reactive systems with Akka
Building reactive systems with Akka
 
Akka framework
Akka frameworkAkka framework
Akka framework
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Networks and Types - the Future of Akka @ ScalaDays NYC 2018Networks and Types - the Future of Akka @ ScalaDays NYC 2018
Networks and Types - the Future of Akka @ ScalaDays NYC 2018
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 

More from Meetu Maltiar

Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Fitnesse With Scala
Fitnesse With ScalaFitnesse With Scala
Fitnesse With Scala
Meetu Maltiar
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
Meetu Maltiar
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Meetu Maltiar
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Scala test
Scala testScala test
Scala test
Meetu Maltiar
 
Scala Collections
Scala CollectionsScala Collections
Scala Collections
Meetu Maltiar
 
Easy ORMness with Objectify-Appengine
Easy ORMness with Objectify-AppengineEasy ORMness with Objectify-Appengine
Easy ORMness with Objectify-Appengine
Meetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 

More from Meetu Maltiar (9)

Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Fitnesse With Scala
Fitnesse With ScalaFitnesse With Scala
Fitnesse With Scala
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala test
Scala testScala test
Scala test
 
Scala Collections
Scala CollectionsScala Collections
Scala Collections
 
Easy ORMness with Objectify-Appengine
Easy ORMness with Objectify-AppengineEasy ORMness with Objectify-Appengine
Easy ORMness with Objectify-Appengine
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 

Recently uploaded

IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
PriyankaKilaniya
 
Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
Kamal Acharya
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
ijaia
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
mahaffeycheryld
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
AjmalKhan50578
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
Yasser Mahgoub
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
CVCSOfficial
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 

Recently uploaded (20)

IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
 
Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 

Introducing Akka

  • 1. Introducing Akka Meetu Maltiar Cisco blog: meetumaltiar.wordpress.com twitter: @meetumaltiar 28th June 2014
  • 2. Agenda History of Akka Scala basics The use case of Akka Akka Actors Akka Supervision
  • 3. History Philipp 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
  • 5. Scala Basics Scala 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
  • 6. Scala Compared To Java Scala 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
  • 7. 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
  • 8. Scala Cheat Sheet(2) definitions Scala 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; } }
  • 9. Scala: Pattern Matching All 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
  • 10. Akka The 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!!
  • 11. The Problem It is way to hard to build => correct highly concurrent systems => Truly scalable systems => self-healing, fault-tolerant systems
  • 12. 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
  • 13. Right Abstraction Never 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
  • 14. Actor Model Actor 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
  • 15. Introducing Actors Actor 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
  • 16. 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.
  • 17. Mailbox Actor having behaviour, state and a mailbox Messages are in mailbox No thread is allocated to the Actor
  • 18. Thread is allocated to the Actor It is now ready to read message and apply behaviour Mailbox
  • 19. Thread is allocated to the Actor It has read message and is applying behaviour Mailbox
  • 20. Mailbox Actor has handled message Thread is deallocated It will be allocated a thread later
  • 21. Create Actor System ActorSystem 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")
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. Ask Pattern package com.meetu.akka ! import akka.actor._ import akka.pattern.ask import akka.util.Timeout import scala.concurrent.duration._ import scala.concurrent.Await import 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
  • 27. 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
  • 29. Round Robin Router import akka.actor._ import akka.routing.RoundRobinPool import 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
  • 30. Failure: Typical Scenario There 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
  • 31. 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
  • 32. …Let’s take a standard OO application
  • 33. Which components have critically important state and Explicit error handling
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39. Supervise Actor Every 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
  • 40. Supervision Actor class 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) } }
  • 41. Supervision: Child Actor class Child extends Actor { var state = 0 def receive = { case ex: Exception => throw ex case x: Int => state = x case "get" => sender ! state } }
  • 42. Supervision Application object 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]) }
  • 44. Learning Resources Code examples at Github https://github.com/meetumaltiar/AkkaQuickStart ! Akka Documentation http://akka.io/docs/ ! Scala Documentation http://www.scala-lang.org/documentation/