SlideShare a Scribd company logo
1 of 31
Download to read offline
Type Safe
Actors
Konrad Malawski, Akka Team(Johan Andrén got sick…)
JFokus, Stockholm, 2018-02-07
Next generation
with Akka
Konrad `ktoso` Malawski
Akka Team
Reactive Streams TCK
Scala Library Improvement Process Committee Member
akka.io
typesafe.com
geecon.org
Java.pl / KrakowScala.pl
sckrk.com / meetup.com/Paper-Cup @ London
GDGKrakow.pl
lambdakrk.pl
Build powerful reactive, concurrent,
and distributed applications more easily
Akka
Actors – simple & high performance concurrency
Cluster, Cluster tools – tools for building distributed systems
Streams – reactive streams implementation
Persistence – CQRS + Event Sourcing for Actors
HTTP – fully async streaming HTTP Server
Alpakka – Reactive Streams Integrations a’la Camel
Complete Java & Scala APIs for all features
What’s in the toolkit?
Actor
Message
Inbox
MessageMessage
Akka Actor Fundamentals
actorRef.tell(message, sender)
actorRef ! message // sender captured implicitly
• mutate state (including spawning a child actor)
• send messages to other actors
• change its behavior
For a message an Actor
Actor
Message
Inbox
MessageMessage
can
Untyped Actors => Akka Typed
Untyped Actors
• “sender()” propagated automatically
• any message type can be sent to any Actor
• actor’s def receive = { … } don’t return values
Untyped Actors => Akka Typed
Untyped Actors
• “sender()” propagated automatically
• any message type can be sent to any Actor
• actor’s def receive = { … } don’t return values
Akka Typed Actors
• “sender” is part of the protocol
• only the right type of messages can be sent: 

ActorRef[MessageProtocol]
• behaviors always return new behaviors

(state machines for the win)
Quick reminder (Untyped):
class MyActor extends Actor {
def receive = {
case Msg(a) =>
sender() ! “Hi there!”
// …
}
}
Sample
Burglar Alarm
• enabled/disabled with a pin code
• accepts notifications about “activity”
• if enabled on activity, sound the alarm
// message protocol
trait AlarmMessage
case class EnableAlarm(pinCode: String) extends AlarmMessage
case class DisableAlarm(pinCode: String) extends AlarmMessage
case object ActivityEvent extends AlarmMessage
// behavior
def enabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case DisableAlarm(enteredCode) if enteredCode == pinCode =>
ctx.log.info("Disabling alarm")
disabled(pinCode) // change behavior
case ActivityEvent =>
ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!")
Behaviors.same
case _ =>
Behaviors.ignore
}
}
def disabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case EnableAlarm(enteredCode) if enteredCode == pinCode =>
enabled(pinCode) // change behavior
case _ =>
Behaviors.ignore
}
}
// behavior
def enabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case DisableAlarm(enteredCode) if enteredCode == pinCode =>
ctx.log.info("Disabling alarm")
disabled(pinCode) // change behavior
case ActivityEvent =>
ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!")
Behaviors.same
case _ =>
Behaviors.ignore
}
}
def disabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case EnableAlarm(enteredCode) if enteredCode == pinCode =>
enabled(pinCode) // change behavior
case _ =>
Behaviors.ignore
}
}
// behavior
def enabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case DisableAlarm(enteredCode) if enteredCode == pinCode =>
ctx.log.info("Disabling alarm")
disabled(pinCode) // change behavior
case ActivityEvent =>
ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!")
Behaviors.same
case _ =>
Behaviors.ignore
}
}
def disabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case EnableAlarm(enteredCode) if enteredCode == pinCode =>
enabled(pinCode) // change behavior
case _ =>
Behaviors.ignore
}
}
// behavior
def enabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case DisableAlarm(enteredCode) if enteredCode == pinCode =>
ctx.log.info("Disabling alarm")
disabled(pinCode) // change behavior
case ActivityEvent =>
ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!")
Behaviors.same
case _ =>
Behaviors.ignore
}
}
def disabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case EnableAlarm(enteredCode) if enteredCode == pinCode =>
enabled(pinCode) // change behavior
case _ =>
Behaviors.ignore
}
}
// behavior
def enabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case DisableAlarm(enteredCode) if enteredCode == pinCode =>
ctx.log.info("Disabling alarm")
disabled(pinCode) // change behavior
case ActivityEvent =>
ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!")
Behaviors.same
case _ =>
Behaviors.ignore
}
}
def disabled(pinCode: String): Behavior[AlarmMessage] =
Behaviors.immutable[AlarmMessage] { (ctx, msg) =>
msg match {
case EnableAlarm(enteredCode) if enteredCode == pinCode =>
enabled(pinCode) // change behavior
case _ =>
Behaviors.ignore
}
}
// running it
val system = ActorSystem(enabled("0000"), "AlarmSystem")
// system is also reference to top level actor
val alarmRef: ActorRef[AlarmMessage] = system
alarmRef ! DisableAlarm("1234")
alarmRef ! ActivityEvent
alarmRef ! DisableAlarm("0000")
alarmRef ! ActivityEvent
alarmRef ! EnableAlarm("0000")
// running it
val system = ActorSystem(enabled("0000"), "AlarmSystem")
// system is also reference to top level actor
val alarmRef: ActorRef[AlarmMessage] = system
alarmRef ! DisableAlarm("1234")
alarmRef ! ActivityEvent
alarmRef ! DisableAlarm("0000")
alarmRef ! ActivityEvent
alarmRef ! EnableAlarm(“0000")
alarmRef ! ”0000” // compile error
Local
ActorSystem
Message
Message
Actor
Actor
Actor
JVM 2
JVM 1
Distributed
ActorSystem
ActorSystem
Message
Message
Actor
Actor
Actor
location transparency => no code changes
Akka Cluster
ActorSystem ActorSystem
ActorSystem
Receptionist
Receptionist
Receptionist
Receptionist
Subscribe(key, actorRef)
Register(Key[AlarmMessage],
ActorRef[AlarmMessage])
ActorRef[AlarmMessage]
ActorRef[SensorEvent]
Sample
Distributed Burglar Alarm
• we can have any number of nodes
• a sensor on any node can report activity to the alarm
val receptionist = Receptionist(system).ref
val alarmKey = ServiceKey[AlarmMessage]("alarm")
def startAlarm(pinCode: String): Behavior[AlarmMessage] =
Behaviors.deferred { ctx =>
receptionist ! Register(alarmKey, ctx.self, ctx.system.deadLetters)
enabled(pinCode)
}
val receptionist = Receptionist(system).ref
val alarmKey = ServiceKey[AlarmMessage]("alarm")
def startAlarm(pinCode: String): Behavior[AlarmMessage] =
Behaviors.deferred { ctx =>
receptionist ! Register(alarmKey, ctx.self, ctx.system.deadLetters)
enabled(pinCode)
}
// protocol
trait SensorEvent
case object WindowOpened extends SensorEvent
// behavior
def sensorBehavior: Behavior[SensorEvent] =
Behaviors.deferred { ctx =>
var alarms = Set.empty[ActorRef[AlarmMessage]]
Receptionist(ctx.system).ref ! Receptionist.Subscribe(
alarmKey, ctx.self.narrow[Listing[AlarmMessage]])
Behaviors.immutable[Any]((ctx, msg) =>
msg match {
case Listing(_, updatedAlarms: Set[ActorRef[AlarmMessage]]) =>
// updated list of alarms known
alarms = updatedAlarms
Behaviors.same
case WindowOpened =>
// inform all known alarms about activity
alarms.foreach(_ ! ActivityEvent)
Behaviors.same
}
)
}.narrow // narrow Behavior[Any] down to Behavior[SensorEvent]
// protocol
trait SensorEvent
case object WindowOpened extends SensorEvent
// behavior
def sensorBehavior: Behavior[SensorEvent] =
Behaviors.deferred { ctx =>
var alarms = Set.empty[ActorRef[AlarmMessage]]
Receptionist(ctx.system).ref ! Receptionist.Subscribe(
alarmKey, ctx.self.narrow[Listing[AlarmMessage]])
Behaviors.immutable[Any]((ctx, msg) =>
msg match {
case Listing(_, updatedAlarms: Set[ActorRef[AlarmMessage]]) =>
// updated list of alarms known
alarms = updatedAlarms
Behaviors.same
case WindowOpened =>
// inform all known alarms about activity
alarms.foreach(_ ! ActivityEvent)
Behaviors.same
}
)
}.narrow // narrow Behavior[Any] down to Behavior[SensorEvent]
// protocol
trait SensorEvent
case object WindowOpened extends SensorEvent
// behavior
def sensorBehavior: Behavior[SensorEvent] =
Behaviors.deferred { ctx =>
var alarms = Set.empty[ActorRef[AlarmMessage]]
Receptionist(ctx.system).ref ! Receptionist.Subscribe(
alarmKey, ctx.self.narrow[Listing[AlarmMessage]])
Behaviors.immutable[Any]((ctx, msg) =>
msg match {
case Listing(_, updatedAlarms: Set[ActorRef[AlarmMessage]]) =>
// updated list of alarms known
alarms = updatedAlarms
Behaviors.same
case WindowOpened =>
// inform all known alarms about activity
alarms.foreach(_ ! ActivityEvent)
Behaviors.same
}
)
}.narrow // narrow Behavior[Any] down to Behavior[SensorEvent]
class SensorBehavior(ctx: ActorContext[SensorProtocol]) extends MutableBehavior[SensorProtocol] {
private var alarms = Set.empty[ActorRef[AlarmMessage]]
private val receptionist: ActorRef[Receptionist.Command] = Receptionist(ctx.system).ref
ctx.ask(receptionist)(Receptionist.Subscribe(alarmKey, _))(res AlarmListing(res.get.serviceInstances))
override def onMessage(msg: SensorProtocol): Behavior[SensorProtocol] = msg match {
case AlarmListing(updatedAlarms) =>
// updated list of alarms known
alarms = updatedAlarms
this
case WindowOpened =>
// inform all known alarms about activity
alarms.foreach(_ ! ActivityEvent)
this
}
}
“Mutable”Behavior:
// running it
val system1 = ActorSystem(startAlarm("0000"), "AlarmSystem")
val system2 = ActorSystem(sensorBehavior, "AlarmSystem")
// programmatic cluster formation
val node1 = Cluster(system1)
val node2 = Cluster(system2)
// node1 joins itself to form cluster
node1.manager ! Join(node1.selfMember.address)
// node2 joins the now existing cluster
node2.manager ! Join(node1.selfMember.address)
// a bit later the burglar comes
after(1.day) {
system2 ! WindowOpened
}
Thanks for listening!
Konrad ktoso@lightbend.com Malawski
http://kto.so / @ktosopl
Akka docs: akka.io/docs
Free O’Reilly report – bit.ly/why-reactive

More Related Content

What's hot

What's hot (20)

Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
 
Hamcrest
HamcrestHamcrest
Hamcrest
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Guice2.0
Guice2.0Guice2.0
Guice2.0
 
Introduction toandroid
Introduction toandroidIntroduction toandroid
Introduction toandroid
 
Akka
AkkaAkka
Akka
 
A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with Xtend
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
 
AutoComplete
AutoCompleteAutoComplete
AutoComplete
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
Call Back
Call BackCall Back
Call Back
 
Tech fest
Tech festTech fest
Tech fest
 

Similar to Akka Typed (quick talk) - JFokus 2018

Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
Maciej Matyjas
 
Akka persistence webinar
Akka persistence webinarAkka persistence webinar
Akka persistence webinar
patriknw
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Vaclav Pech
 

Similar to Akka Typed (quick talk) - JFokus 2018 (20)

Networks and types - the future of Akka
Networks and types - the future of AkkaNetworks and types - the future of Akka
Networks and types - the future of Akka
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
Android wearpp
Android wearppAndroid wearpp
Android wearpp
 
Thirteen ways of looking at a turtle
Thirteen ways of looking at a turtleThirteen ways of looking at a turtle
Thirteen ways of looking at a turtle
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
 
Akka knolx
Akka knolxAkka knolx
Akka knolx
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
Next generation actors with Akka
Next generation actors with AkkaNext generation actors with Akka
Next generation actors with Akka
 
Akka Testkit Patterns
Akka Testkit PatternsAkka Testkit Patterns
Akka Testkit Patterns
 
Meet scala
Meet scalaMeet scala
Meet scala
 
[4developers] The saga pattern v3- Robert Pankowiecki
[4developers] The saga pattern v3- Robert Pankowiecki[4developers] The saga pattern v3- Robert Pankowiecki
[4developers] The saga pattern v3- Robert Pankowiecki
 
Improving Correctness with Types
Improving Correctness with TypesImproving Correctness with Types
Improving Correctness with Types
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
 
Akka persistence webinar
Akka persistence webinarAkka persistence webinar
Akka persistence webinar
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
2 years after the first event - The Saga Pattern
2 years after the first event - The Saga Pattern2 years after the first event - The Saga Pattern
2 years after the first event - The Saga Pattern
 

More from Konrad Malawski

Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Konrad Malawski
 

More from Konrad Malawski (20)

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
 
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in'tScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
 
State of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeState of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to come
 
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYCBuilding a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
Building a Reactive System with Akka - Workshop @ O'Reilly SAConf NYC
 
Akka-chan's Survival Guide for the Streaming World
Akka-chan's Survival Guide for the Streaming WorldAkka-chan's Survival Guide for the Streaming World
Akka-chan's Survival Guide for the Streaming World
 
Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
 
Not Only Streams for Akademia JLabs
Not Only Streams for Akademia JLabsNot Only Streams for Akademia JLabs
Not Only Streams for Akademia JLabs
 
Reactive Streams, j.u.concurrent & Beyond!
Reactive Streams, j.u.concurrent & Beyond!Reactive Streams, j.u.concurrent & Beyond!
Reactive Streams, j.u.concurrent & Beyond!
 
End to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to SocketEnd to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to Socket
 
The Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOneThe Cloud-natives are RESTless @ JavaOne
The Cloud-natives are RESTless @ JavaOne
 
Akka Streams in Action @ ScalaDays Berlin 2016
Akka Streams in Action @ ScalaDays Berlin 2016Akka Streams in Action @ ScalaDays Berlin 2016
Akka Streams in Action @ ScalaDays Berlin 2016
 
Krakow communities @ 2016
Krakow communities @ 2016Krakow communities @ 2016
Krakow communities @ 2016
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK
100th SCKRK Meeting - best software engineering papers of 5 years of SCKRK
 
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...
[Japanese] How Reactive Streams and Akka Streams change the JVM Ecosystem @ R...
 
Zen of Akka
Zen of AkkaZen of Akka
Zen of Akka
 
How Reactive Streams & Akka Streams change the JVM Ecosystem
How Reactive Streams & Akka Streams change the JVM EcosystemHow Reactive Streams & Akka Streams change the JVM Ecosystem
How Reactive Streams & Akka Streams change the JVM Ecosystem
 
The Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorld
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
 
Need for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applicationsNeed for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applications
 

Recently uploaded

Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
chumtiyababu
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 

Recently uploaded (20)

Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 

Akka Typed (quick talk) - JFokus 2018

  • 1. Type Safe Actors Konrad Malawski, Akka Team(Johan Andrén got sick…) JFokus, Stockholm, 2018-02-07 Next generation with Akka
  • 2. Konrad `ktoso` Malawski Akka Team Reactive Streams TCK Scala Library Improvement Process Committee Member akka.io typesafe.com geecon.org Java.pl / KrakowScala.pl sckrk.com / meetup.com/Paper-Cup @ London GDGKrakow.pl lambdakrk.pl
  • 3. Build powerful reactive, concurrent, and distributed applications more easily Akka
  • 4. Actors – simple & high performance concurrency Cluster, Cluster tools – tools for building distributed systems Streams – reactive streams implementation Persistence – CQRS + Event Sourcing for Actors HTTP – fully async streaming HTTP Server Alpakka – Reactive Streams Integrations a’la Camel Complete Java & Scala APIs for all features What’s in the toolkit?
  • 5. Actor Message Inbox MessageMessage Akka Actor Fundamentals actorRef.tell(message, sender) actorRef ! message // sender captured implicitly
  • 6. • mutate state (including spawning a child actor) • send messages to other actors • change its behavior For a message an Actor Actor Message Inbox MessageMessage can
  • 7. Untyped Actors => Akka Typed Untyped Actors • “sender()” propagated automatically • any message type can be sent to any Actor • actor’s def receive = { … } don’t return values
  • 8. Untyped Actors => Akka Typed Untyped Actors • “sender()” propagated automatically • any message type can be sent to any Actor • actor’s def receive = { … } don’t return values Akka Typed Actors • “sender” is part of the protocol • only the right type of messages can be sent: 
 ActorRef[MessageProtocol] • behaviors always return new behaviors
 (state machines for the win)
  • 9. Quick reminder (Untyped): class MyActor extends Actor { def receive = { case Msg(a) => sender() ! “Hi there!” // … } }
  • 10. Sample Burglar Alarm • enabled/disabled with a pin code • accepts notifications about “activity” • if enabled on activity, sound the alarm
  • 11. // message protocol trait AlarmMessage case class EnableAlarm(pinCode: String) extends AlarmMessage case class DisableAlarm(pinCode: String) extends AlarmMessage case object ActivityEvent extends AlarmMessage
  • 12. // behavior def enabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case DisableAlarm(enteredCode) if enteredCode == pinCode => ctx.log.info("Disabling alarm") disabled(pinCode) // change behavior case ActivityEvent => ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!") Behaviors.same case _ => Behaviors.ignore } } def disabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case EnableAlarm(enteredCode) if enteredCode == pinCode => enabled(pinCode) // change behavior case _ => Behaviors.ignore } }
  • 13. // behavior def enabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case DisableAlarm(enteredCode) if enteredCode == pinCode => ctx.log.info("Disabling alarm") disabled(pinCode) // change behavior case ActivityEvent => ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!") Behaviors.same case _ => Behaviors.ignore } } def disabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case EnableAlarm(enteredCode) if enteredCode == pinCode => enabled(pinCode) // change behavior case _ => Behaviors.ignore } }
  • 14. // behavior def enabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case DisableAlarm(enteredCode) if enteredCode == pinCode => ctx.log.info("Disabling alarm") disabled(pinCode) // change behavior case ActivityEvent => ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!") Behaviors.same case _ => Behaviors.ignore } } def disabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case EnableAlarm(enteredCode) if enteredCode == pinCode => enabled(pinCode) // change behavior case _ => Behaviors.ignore } }
  • 15. // behavior def enabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case DisableAlarm(enteredCode) if enteredCode == pinCode => ctx.log.info("Disabling alarm") disabled(pinCode) // change behavior case ActivityEvent => ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!") Behaviors.same case _ => Behaviors.ignore } } def disabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case EnableAlarm(enteredCode) if enteredCode == pinCode => enabled(pinCode) // change behavior case _ => Behaviors.ignore } }
  • 16. // behavior def enabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case DisableAlarm(enteredCode) if enteredCode == pinCode => ctx.log.info("Disabling alarm") disabled(pinCode) // change behavior case ActivityEvent => ctx.log.warning("OEOEOEOEOEOE alarm, activity detected!") Behaviors.same case _ => Behaviors.ignore } } def disabled(pinCode: String): Behavior[AlarmMessage] = Behaviors.immutable[AlarmMessage] { (ctx, msg) => msg match { case EnableAlarm(enteredCode) if enteredCode == pinCode => enabled(pinCode) // change behavior case _ => Behaviors.ignore } }
  • 17. // running it val system = ActorSystem(enabled("0000"), "AlarmSystem") // system is also reference to top level actor val alarmRef: ActorRef[AlarmMessage] = system alarmRef ! DisableAlarm("1234") alarmRef ! ActivityEvent alarmRef ! DisableAlarm("0000") alarmRef ! ActivityEvent alarmRef ! EnableAlarm("0000")
  • 18. // running it val system = ActorSystem(enabled("0000"), "AlarmSystem") // system is also reference to top level actor val alarmRef: ActorRef[AlarmMessage] = system alarmRef ! DisableAlarm("1234") alarmRef ! ActivityEvent alarmRef ! DisableAlarm("0000") alarmRef ! ActivityEvent alarmRef ! EnableAlarm(“0000") alarmRef ! ”0000” // compile error
  • 23. Sample Distributed Burglar Alarm • we can have any number of nodes • a sensor on any node can report activity to the alarm
  • 24. val receptionist = Receptionist(system).ref val alarmKey = ServiceKey[AlarmMessage]("alarm") def startAlarm(pinCode: String): Behavior[AlarmMessage] = Behaviors.deferred { ctx => receptionist ! Register(alarmKey, ctx.self, ctx.system.deadLetters) enabled(pinCode) }
  • 25. val receptionist = Receptionist(system).ref val alarmKey = ServiceKey[AlarmMessage]("alarm") def startAlarm(pinCode: String): Behavior[AlarmMessage] = Behaviors.deferred { ctx => receptionist ! Register(alarmKey, ctx.self, ctx.system.deadLetters) enabled(pinCode) }
  • 26. // protocol trait SensorEvent case object WindowOpened extends SensorEvent // behavior def sensorBehavior: Behavior[SensorEvent] = Behaviors.deferred { ctx => var alarms = Set.empty[ActorRef[AlarmMessage]] Receptionist(ctx.system).ref ! Receptionist.Subscribe( alarmKey, ctx.self.narrow[Listing[AlarmMessage]]) Behaviors.immutable[Any]((ctx, msg) => msg match { case Listing(_, updatedAlarms: Set[ActorRef[AlarmMessage]]) => // updated list of alarms known alarms = updatedAlarms Behaviors.same case WindowOpened => // inform all known alarms about activity alarms.foreach(_ ! ActivityEvent) Behaviors.same } ) }.narrow // narrow Behavior[Any] down to Behavior[SensorEvent]
  • 27. // protocol trait SensorEvent case object WindowOpened extends SensorEvent // behavior def sensorBehavior: Behavior[SensorEvent] = Behaviors.deferred { ctx => var alarms = Set.empty[ActorRef[AlarmMessage]] Receptionist(ctx.system).ref ! Receptionist.Subscribe( alarmKey, ctx.self.narrow[Listing[AlarmMessage]]) Behaviors.immutable[Any]((ctx, msg) => msg match { case Listing(_, updatedAlarms: Set[ActorRef[AlarmMessage]]) => // updated list of alarms known alarms = updatedAlarms Behaviors.same case WindowOpened => // inform all known alarms about activity alarms.foreach(_ ! ActivityEvent) Behaviors.same } ) }.narrow // narrow Behavior[Any] down to Behavior[SensorEvent]
  • 28. // protocol trait SensorEvent case object WindowOpened extends SensorEvent // behavior def sensorBehavior: Behavior[SensorEvent] = Behaviors.deferred { ctx => var alarms = Set.empty[ActorRef[AlarmMessage]] Receptionist(ctx.system).ref ! Receptionist.Subscribe( alarmKey, ctx.self.narrow[Listing[AlarmMessage]]) Behaviors.immutable[Any]((ctx, msg) => msg match { case Listing(_, updatedAlarms: Set[ActorRef[AlarmMessage]]) => // updated list of alarms known alarms = updatedAlarms Behaviors.same case WindowOpened => // inform all known alarms about activity alarms.foreach(_ ! ActivityEvent) Behaviors.same } ) }.narrow // narrow Behavior[Any] down to Behavior[SensorEvent]
  • 29. class SensorBehavior(ctx: ActorContext[SensorProtocol]) extends MutableBehavior[SensorProtocol] { private var alarms = Set.empty[ActorRef[AlarmMessage]] private val receptionist: ActorRef[Receptionist.Command] = Receptionist(ctx.system).ref ctx.ask(receptionist)(Receptionist.Subscribe(alarmKey, _))(res AlarmListing(res.get.serviceInstances)) override def onMessage(msg: SensorProtocol): Behavior[SensorProtocol] = msg match { case AlarmListing(updatedAlarms) => // updated list of alarms known alarms = updatedAlarms this case WindowOpened => // inform all known alarms about activity alarms.foreach(_ ! ActivityEvent) this } } “Mutable”Behavior:
  • 30. // running it val system1 = ActorSystem(startAlarm("0000"), "AlarmSystem") val system2 = ActorSystem(sensorBehavior, "AlarmSystem") // programmatic cluster formation val node1 = Cluster(system1) val node2 = Cluster(system2) // node1 joins itself to form cluster node1.manager ! Join(node1.selfMember.address) // node2 joins the now existing cluster node2.manager ! Join(node1.selfMember.address) // a bit later the burglar comes after(1.day) { system2 ! WindowOpened }
  • 31. Thanks for listening! Konrad ktoso@lightbend.com Malawski http://kto.so / @ktosopl Akka docs: akka.io/docs Free O’Reilly report – bit.ly/why-reactive