SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
A gentle
introduction
into AKKA and
the actor model
Mike Kotsur, 2016
github.com/mkotsur
Goals
• A problem (one of them) and traditional solutions
• Actor Model (since 1973)
• Akka Actors
• The rest of Akka goodies
• To choose, or not to choose (Akka)
2 ways
• Simplicity
• Speed
[1] Herb Sutter. The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software, 2005. –
http://www.gotw.ca/publications/concurrency-ddj.htm
Concurrency is the
next major revolution
in how we write
software [1].
More CPUs —
more threads
Your code:
if (check (seat, row))
book (seat, row)
More CPUs — more threads
check (1, 10)
book (1, 10)
check (1, 10)
book (1, 10)
check (1, 10)
check (1, 10)
book (1, 10)
book (1, 10)
:-(
But we have smart databases!
• Managing shared state requires synchronisation;
• Which leads to keeping the threads busy waiting;
• The granularity control is limited;
• There are different solutions to the problem:
• synchronized,
• database,
• something else?
– Carl Hewitt
“An actor is the fundamental unit of
computation which embodies the 3 things –
processing, storage and communications – that
are essential to computation.”
What an actor is not…
Future Thread Actor
Processing + + +
Storage + +
Communication +
What an actor can do?
• Designate how to handle the next message it
receives;
• Create new actors;
• Send messages to actors it knows.
Messages
• Processed one at a time;
• May be not delivered in the same order as sent;
• At-most-once delivery guarantee.
Why actors are interesting?
• Unified model for concurrency and parallelism;
• Out-of-the box multi-server support.
Could we use this to sell
tickets?
Actors in 22 lines
https://gist.github.com/viktorklang/2362563
➡ Actors
• Persistence
• Networking
• Clustering
• Streams
• HTTP
• Testkits
object TicketDeskActor {
case class BookTicket(eventId: String,
row: Int,
seat: Int)
case class TicketBooked(ticketId: Long)
}
class TicketDeskActor extends Actor {
override def receive: Receive = {
case BookTicket(eventId, row, seat) => ???
}
}
val mySystem = ActorSystem("TheatreApp")
val myProps: Props = Props[TicketDeskActor]
val myActor: ActorRef = mySystem.
actorOf(myProps, "ticket-desk")
print(s"Created ${myActor.path}")
// Created akka://TheatreApp/user/ticket-desk
mySystem.terminate()
Actor recipe
Actor path
Actor ref
val result: Future[Any] = myActor ? BookTicket(…)
myActor ! BookTicket(…)
Tell (a.k.a. “fire and forget”)
Ask
More about messaging
tomorrow
class TicketDeskActor extends Actor {
override def receive: Receive = {
case msg @ BookTicket(eventId, _, _) =>
val evtActorName = s"event-$eventId"
val evtActorProps = Props(new
EventActor(eventId))
val eventActorRef =
context.child(evtActorName).getOrElse {
context.actorOf(evtActorProps,
evtActorName)
}
eventActorRef forward msg
}
}
class EventActor(eventId: String) extends Actor with ActorLogging {
override def preStart(): Unit = {
log.info(s"Starting an event actor for $eventId")
}
override def receive: Receive = {
case BookTicket(_, seat, row) =>
log.info("Updating the state with the newly booked ticket")
}
}
[INFO] [04/03/2016 20:17:57.907] [TheatreApp-akka.actor.default-
dispatcher-3] [akka://TheatreApp/user/ticket-desk/event-
JustinBieber] Starting an event actor for JustinBieber
Actor path
Logging trait
Changing the behaviour: delayed sales example.
object DelayedEventActor {
case object SaleIsNotStartedYet
case object StartSale
}
class DelayedEventActor(eventId: String, saleStarts: LocalDateTime)
extends EventActor(eventId) with ActorLogging {
var cancellable: Option[Cancellable] = None
override def preStart(): Unit = {
super.preStart()
val delay = Duration.between(saleStarts, LocalDateTime.now())
import context.dispatcher
cancellable = Some(
context.system.scheduler.scheduleOnce(delay.toNanos nanos, self, StartSale)
)
}
override def postStop(): Unit = {
super.postStop()
cancellable.foreach(_.cancel())
}
override def receive: Receive = {
case StartSale =>
context.become(super.receive)
case msg: BookTicket =>
log.warning(s"Trying to book a ticket too early")
sender() ! SaleIsNotStartedYet
}
}
Scheduling a message to self
Changing the behaviour
Extends the normal EventActor
Lifecycle: stopping
• Actors can be terminated by stop() or PoisonPill
message;
• postStop() method is called;
• The rest of the messages is sent to the dead
letters;
• If an actor is terminated, all its children are
terminated as well.
Lifecycle: fault tolerance
• Supervision by parent actors;
• On exception: Resume, Restart, Stop, or
Escalate, based on the supervision strategy;
But what about persistence?
Traditional way:
Persisting the state
Event sourcing:
persisting the events
Clustering
• Actor model is very good for clustering;
• Akka has very good clustering support:
• Sharding;
• Cluster singleton;
• Other stuff. Check it out.
Is Akka a good choice for
you?
Paul Chiusano: Actors are
overly nondeterminstic :-(
Roland Kuhn: …they are the
essence of concurrency and
therefore by nature as non-
deterministic as they can be.
Actors are overly nondeterminstic, Paul Chiusano's blog, 2013 — http://pchiusano.blogspot.nl/2013/09/actors-are-
overly-nondeterminstic.html
How to start?
• Find a task where the advantage is obvious!
• Micro service Pet-project scale first?
• The structure and lifecycle is important!
What next?
Thanks.
Some code is here:
https://github.com/mkotsur/actors-introduction
And let’s chat!

Weitere ähnliche Inhalte

Was ist angesagt?

Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupApcera
 
Actor model in .NET - Akka.NET
Actor model in .NET - Akka.NETActor model in .NET - Akka.NET
Actor model in .NET - Akka.NETKonrad Dusza
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to AkkaKnoldus Inc.
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterKonstantin Tsykulenko
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayYardena Meymann
 
Project Orleans - Actor Model framework
Project Orleans - Actor Model frameworkProject Orleans - Actor Model framework
Project Orleans - Actor Model frameworkNeil Mackenzie
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debuggerIulian Dragos
 
Actors Set the Stage for Project Orleans
Actors Set the Stage for Project OrleansActors Set the Stage for Project Orleans
Actors Set the Stage for Project Orleanscjmyers
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений БобровFwdays
 
Reactive programming with scala and akka
Reactive programming with scala and akkaReactive programming with scala and akka
Reactive programming with scala and akkaKnoldus Inc.
 
CQRS + ES with Scala and Akka
CQRS + ES with Scala and AkkaCQRS + ES with Scala and Akka
CQRS + ES with Scala and AkkaBharadwaj N
 
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 2018Konrad Malawski
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akkanartamonov
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matterSkills Matter
 
JVM languages "flame wars"
JVM languages "flame wars"JVM languages "flame wars"
JVM languages "flame wars"Gal Marder
 

Was ist angesagt? (20)

Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Actor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder MeetupActor Patterns and NATS - Boulder Meetup
Actor Patterns and NATS - Boulder Meetup
 
Actor model in .NET - Akka.NET
Actor model in .NET - Akka.NETActor model in .NET - Akka.NET
Actor model in .NET - Akka.NET
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Akka Actors
Akka ActorsAkka Actors
Akka Actors
 
Introduction to the Actor Model
Introduction to the Actor ModelIntroduction to the Actor Model
Introduction to the Actor Model
 
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
 
Project Orleans - Actor Model framework
Project Orleans - Actor Model frameworkProject Orleans - Actor Model framework
Project Orleans - Actor Model framework
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Actors Set the Stage for Project Orleans
Actors Set the Stage for Project OrleansActors Set the Stage for Project Orleans
Actors Set the Stage for Project Orleans
 
Akka.Net Overview
Akka.Net OverviewAkka.Net Overview
Akka.Net Overview
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
 
Reactive programming with scala and akka
Reactive programming with scala and akkaReactive programming with scala and akka
Reactive programming with scala and akka
 
CQRS + ES with Scala and Akka
CQRS + ES with Scala and AkkaCQRS + ES with Scala and Akka
CQRS + ES with Scala and Akka
 
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
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
JVM languages "flame wars"
JVM languages "flame wars"JVM languages "flame wars"
JVM languages "flame wars"
 
3 years with Clojure
3 years with Clojure3 years with Clojure
3 years with Clojure
 

Andere mochten auch

РИФ 2016, РЫНОК ВИДЕОРЕКЛАМЫ В РОССИИ ТРЕНДЫ И ПЕРСПЕКТИВЫ
РИФ 2016, РЫНОК ВИДЕОРЕКЛАМЫ В РОССИИ ТРЕНДЫ И ПЕРСПЕКТИВЫРИФ 2016, РЫНОК ВИДЕОРЕКЛАМЫ В РОССИИ ТРЕНДЫ И ПЕРСПЕКТИВЫ
РИФ 2016, РЫНОК ВИДЕОРЕКЛАМЫ В РОССИИ ТРЕНДЫ И ПЕРСПЕКТИВЫТарасов Константин
 
Adjustments of Toys for Disabled Kids
Adjustments of Toys for Disabled KidsAdjustments of Toys for Disabled Kids
Adjustments of Toys for Disabled KidsNSTDA THAILAND
 
Los Planetas
Los PlanetasLos Planetas
Los Planetasjosemi4d
 
By AG DeltaplanРегиональный рунетTO BE, OR NOT TO BE
By AG DeltaplanРегиональный рунетTO BE, OR NOT TO BEBy AG DeltaplanРегиональный рунетTO BE, OR NOT TO BE
By AG DeltaplanРегиональный рунетTO BE, OR NOT TO BEТарасов Константин
 
РИФ 2016, Естественный отбор на рынке образования или почему университеты дол...
РИФ 2016, Естественный отбор на рынке образования или почему университеты дол...РИФ 2016, Естественный отбор на рынке образования или почему университеты дол...
РИФ 2016, Естественный отбор на рынке образования или почему университеты дол...Тарасов Константин
 
Finding the way to success
Finding the way to successFinding the way to success
Finding the way to successFormulaS
 
РИФ 2016, Таргетированная реклама: как снизить стоимость клиента в 3-5 раз
РИФ 2016, Таргетированная реклама: как снизить стоимость клиента в 3-5 разРИФ 2016, Таргетированная реклама: как снизить стоимость клиента в 3-5 раз
РИФ 2016, Таргетированная реклама: как снизить стоимость клиента в 3-5 разТарасов Константин
 
РИФ 2016, История .su, прошлое и настоящее, перспективы роста
РИФ 2016, История .su, прошлое и настоящее, перспективы ростаРИФ 2016, История .su, прошлое и настоящее, перспективы роста
РИФ 2016, История .su, прошлое и настоящее, перспективы ростаТарасов Константин
 
РИФ 2016, Динамическое пакетирование - новые возможности дистрибуции туристич...
РИФ 2016, Динамическое пакетирование - новые возможности дистрибуции туристич...РИФ 2016, Динамическое пакетирование - новые возможности дистрибуции туристич...
РИФ 2016, Динамическое пакетирование - новые возможности дистрибуции туристич...Тарасов Константин
 
РИФ 2016, Нейромаркетинг. Революционные методы увеличения конверсии сайта
РИФ 2016, Нейромаркетинг. Революционные методы увеличения конверсии сайтаРИФ 2016, Нейромаркетинг. Революционные методы увеличения конверсии сайта
РИФ 2016, Нейромаркетинг. Революционные методы увеличения конверсии сайтаТарасов Константин
 

Andere mochten auch (20)

РИФ 2016, РЫНОК ВИДЕОРЕКЛАМЫ В РОССИИ ТРЕНДЫ И ПЕРСПЕКТИВЫ
РИФ 2016, РЫНОК ВИДЕОРЕКЛАМЫ В РОССИИ ТРЕНДЫ И ПЕРСПЕКТИВЫРИФ 2016, РЫНОК ВИДЕОРЕКЛАМЫ В РОССИИ ТРЕНДЫ И ПЕРСПЕКТИВЫ
РИФ 2016, РЫНОК ВИДЕОРЕКЛАМЫ В РОССИИ ТРЕНДЫ И ПЕРСПЕКТИВЫ
 
Adjustments of Toys for Disabled Kids
Adjustments of Toys for Disabled KidsAdjustments of Toys for Disabled Kids
Adjustments of Toys for Disabled Kids
 
Afghan Scouting (Updated 05Sept13)
Afghan Scouting (Updated 05Sept13)Afghan Scouting (Updated 05Sept13)
Afghan Scouting (Updated 05Sept13)
 
Los Planetas
Los PlanetasLos Planetas
Los Planetas
 
By AG DeltaplanРегиональный рунетTO BE, OR NOT TO BE
By AG DeltaplanРегиональный рунетTO BE, OR NOT TO BEBy AG DeltaplanРегиональный рунетTO BE, OR NOT TO BE
By AG DeltaplanРегиональный рунетTO BE, OR NOT TO BE
 
РИФ 2016, Естественный отбор на рынке образования или почему университеты дол...
РИФ 2016, Естественный отбор на рынке образования или почему университеты дол...РИФ 2016, Естественный отбор на рынке образования или почему университеты дол...
РИФ 2016, Естественный отбор на рынке образования или почему университеты дол...
 
Finding the way to success
Finding the way to successFinding the way to success
Finding the way to success
 
РИФ 2016, Таргетированная реклама: как снизить стоимость клиента в 3-5 раз
РИФ 2016, Таргетированная реклама: как снизить стоимость клиента в 3-5 разРИФ 2016, Таргетированная реклама: как снизить стоимость клиента в 3-5 раз
РИФ 2016, Таргетированная реклама: как снизить стоимость клиента в 3-5 раз
 
РИФ 2016, История .su, прошлое и настоящее, перспективы роста
РИФ 2016, История .su, прошлое и настоящее, перспективы ростаРИФ 2016, История .su, прошлое и настоящее, перспективы роста
РИФ 2016, История .su, прошлое и настоящее, перспективы роста
 
РИФ 2016, Динамическое пакетирование - новые возможности дистрибуции туристич...
РИФ 2016, Динамическое пакетирование - новые возможности дистрибуции туристич...РИФ 2016, Динамическое пакетирование - новые возможности дистрибуции туристич...
РИФ 2016, Динамическое пакетирование - новые возможности дистрибуции туристич...
 
Glooq
GlooqGlooq
Glooq
 
Class06
Class06Class06
Class06
 
Skinforfun2009
Skinforfun2009Skinforfun2009
Skinforfun2009
 
Staircasegr
StaircasegrStaircasegr
Staircasegr
 
Fish Report
Fish ReportFish Report
Fish Report
 
Tech quiz prelims
Tech quiz prelimsTech quiz prelims
Tech quiz prelims
 
РИФ 2016, ЮФО: Кластер «РАЭК / Digital»
РИФ 2016, ЮФО: Кластер «РАЭК / Digital»РИФ 2016, ЮФО: Кластер «РАЭК / Digital»
РИФ 2016, ЮФО: Кластер «РАЭК / Digital»
 
Sarobi Flood (Updated 8 Aug 13)
Sarobi Flood (Updated 8 Aug 13)Sarobi Flood (Updated 8 Aug 13)
Sarobi Flood (Updated 8 Aug 13)
 
РИФ 2016, Нейромаркетинг. Революционные методы увеличения конверсии сайта
РИФ 2016, Нейромаркетинг. Революционные методы увеличения конверсии сайтаРИФ 2016, Нейромаркетинг. Революционные методы увеличения конверсии сайта
РИФ 2016, Нейромаркетинг. Революционные методы увеличения конверсии сайта
 
медиасайт
медиасайтмедиасайт
медиасайт
 

Ähnlich wie A gentle introduction into AKKA and the actor model

Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxpetabridge
 
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 StreamsKonrad Malawski
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研vorfeed chen
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaYardena Meymann
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)tarcieri
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016Frank Lyaruu
 
The dark side of Akka and the remedy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedykrivachy
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Akka Microservices Architecture And Design
Akka Microservices Architecture And DesignAkka Microservices Architecture And Design
Akka Microservices Architecture And DesignYaroslav Tkachenko
 
Naked Performance With Clojure
Naked Performance With ClojureNaked Performance With Clojure
Naked Performance With ClojureMetosin Oy
 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)Ortus Solutions, Corp
 
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...Ortus Solutions, Corp
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 

Ähnlich wie A gentle introduction into AKKA and the actor model (20)

Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
 
Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
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
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
 
The dark side of Akka and the remedy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedy
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Akka Microservices Architecture And Design
Akka Microservices Architecture And DesignAkka Microservices Architecture And Design
Akka Microservices Architecture And Design
 
Naked Performance With Clojure
Naked Performance With ClojureNaked Performance With Clojure
Naked Performance With Clojure
 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)
 
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
ITB2019 CBStreams : Accelerate your Functional Programming with the power of ...
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 

Kürzlich hochgeladen

%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 

Kürzlich hochgeladen (20)

%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 

A gentle introduction into AKKA and the actor model

  • 1. A gentle introduction into AKKA and the actor model Mike Kotsur, 2016 github.com/mkotsur
  • 2. Goals • A problem (one of them) and traditional solutions • Actor Model (since 1973) • Akka Actors • The rest of Akka goodies • To choose, or not to choose (Akka)
  • 4. [1] Herb Sutter. The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software, 2005. – http://www.gotw.ca/publications/concurrency-ddj.htm Concurrency is the next major revolution in how we write software [1].
  • 5.
  • 6.
  • 7.
  • 8.
  • 9. More CPUs — more threads Your code: if (check (seat, row)) book (seat, row)
  • 10. More CPUs — more threads check (1, 10) book (1, 10) check (1, 10) book (1, 10) check (1, 10) check (1, 10) book (1, 10) book (1, 10) :-(
  • 11.
  • 12. But we have smart databases!
  • 13. • Managing shared state requires synchronisation; • Which leads to keeping the threads busy waiting; • The granularity control is limited; • There are different solutions to the problem: • synchronized, • database, • something else?
  • 14. – Carl Hewitt “An actor is the fundamental unit of computation which embodies the 3 things – processing, storage and communications – that are essential to computation.”
  • 15.
  • 16. What an actor is not… Future Thread Actor Processing + + + Storage + + Communication +
  • 17. What an actor can do? • Designate how to handle the next message it receives; • Create new actors; • Send messages to actors it knows.
  • 18. Messages • Processed one at a time; • May be not delivered in the same order as sent; • At-most-once delivery guarantee.
  • 19. Why actors are interesting? • Unified model for concurrency and parallelism; • Out-of-the box multi-server support.
  • 20. Could we use this to sell tickets?
  • 21. Actors in 22 lines https://gist.github.com/viktorklang/2362563
  • 22. ➡ Actors • Persistence • Networking • Clustering • Streams • HTTP • Testkits
  • 23.
  • 24. object TicketDeskActor { case class BookTicket(eventId: String, row: Int, seat: Int) case class TicketBooked(ticketId: Long) } class TicketDeskActor extends Actor { override def receive: Receive = { case BookTicket(eventId, row, seat) => ??? } }
  • 25. val mySystem = ActorSystem("TheatreApp") val myProps: Props = Props[TicketDeskActor] val myActor: ActorRef = mySystem. actorOf(myProps, "ticket-desk") print(s"Created ${myActor.path}") // Created akka://TheatreApp/user/ticket-desk mySystem.terminate() Actor recipe Actor path Actor ref
  • 26. val result: Future[Any] = myActor ? BookTicket(…) myActor ! BookTicket(…) Tell (a.k.a. “fire and forget”) Ask
  • 28.
  • 29.
  • 30. class TicketDeskActor extends Actor { override def receive: Receive = { case msg @ BookTicket(eventId, _, _) => val evtActorName = s"event-$eventId" val evtActorProps = Props(new EventActor(eventId)) val eventActorRef = context.child(evtActorName).getOrElse { context.actorOf(evtActorProps, evtActorName) } eventActorRef forward msg } }
  • 31.
  • 32. class EventActor(eventId: String) extends Actor with ActorLogging { override def preStart(): Unit = { log.info(s"Starting an event actor for $eventId") } override def receive: Receive = { case BookTicket(_, seat, row) => log.info("Updating the state with the newly booked ticket") } } [INFO] [04/03/2016 20:17:57.907] [TheatreApp-akka.actor.default- dispatcher-3] [akka://TheatreApp/user/ticket-desk/event- JustinBieber] Starting an event actor for JustinBieber Actor path Logging trait
  • 33. Changing the behaviour: delayed sales example.
  • 34. object DelayedEventActor { case object SaleIsNotStartedYet case object StartSale } class DelayedEventActor(eventId: String, saleStarts: LocalDateTime) extends EventActor(eventId) with ActorLogging { var cancellable: Option[Cancellable] = None override def preStart(): Unit = { super.preStart() val delay = Duration.between(saleStarts, LocalDateTime.now()) import context.dispatcher cancellable = Some( context.system.scheduler.scheduleOnce(delay.toNanos nanos, self, StartSale) ) } override def postStop(): Unit = { super.postStop() cancellable.foreach(_.cancel()) } override def receive: Receive = { case StartSale => context.become(super.receive) case msg: BookTicket => log.warning(s"Trying to book a ticket too early") sender() ! SaleIsNotStartedYet } } Scheduling a message to self Changing the behaviour Extends the normal EventActor
  • 35. Lifecycle: stopping • Actors can be terminated by stop() or PoisonPill message; • postStop() method is called; • The rest of the messages is sent to the dead letters; • If an actor is terminated, all its children are terminated as well.
  • 36. Lifecycle: fault tolerance • Supervision by parent actors; • On exception: Resume, Restart, Stop, or Escalate, based on the supervision strategy;
  • 37. But what about persistence?
  • 38. Traditional way: Persisting the state Event sourcing: persisting the events
  • 39. Clustering • Actor model is very good for clustering; • Akka has very good clustering support: • Sharding; • Cluster singleton; • Other stuff. Check it out.
  • 40. Is Akka a good choice for you? Paul Chiusano: Actors are overly nondeterminstic :-( Roland Kuhn: …they are the essence of concurrency and therefore by nature as non- deterministic as they can be. Actors are overly nondeterminstic, Paul Chiusano's blog, 2013 — http://pchiusano.blogspot.nl/2013/09/actors-are- overly-nondeterminstic.html
  • 41. How to start? • Find a task where the advantage is obvious! • Micro service Pet-project scale first? • The structure and lifecycle is important!
  • 43. Thanks. Some code is here: https://github.com/mkotsur/actors-introduction And let’s chat!