SlideShare a Scribd company logo
1 of 31
Download to read offline
Scalaz 8 vs Akka Actors
Scalar 2018 - Warsaw, Poland
John A. De Goes
@jdegoes - http://degoes.net
WARNING: The talk you are about to see was rejected
from Scala Days 2018 due to extremely disturbing
content. Attendee discretion is advised.
Ultimate Question of Software Development
Ultimate Question of Software Development
How can we bend light so we
can reactively build reactive
microsystems that react to
reacting reactivity???
Answer to the Ultimate Question of Software Development
PartialFunction[Any, Unit]
Input Message
AKA “Actor”
Killer Use Cases for Actors
1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
1. Parallelism
sealed trait Message
case class Chunk(v: Array[Byte])
class ChunkActor extends Actor {
def receive = {
case Chunk(v) => sender ! encrypt(v)
}
}
val chunkActors =
context.actorOf(Props[ChunkActor].
withRouter(RoundRobinPool(4)), name =
"ChunkActors")
…
chunks.foreach (chunk => chunkActors forward
(Chunk(chunk)))
IO.concurrently(chunks.map(encrypt(_)))
Killer Use Cases for Actors
1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
2. Concurrent State
sealed trait Message
case object Get extends Message
case class Inc(value: Int) extends Message
class Counter extends Actor {
var counter: Int = 0
def receive = {
case Get => sender ! counter
case Inc(v) =>
counter += v
sender ! counter
}
}
...
val system = ActorSystem("counter")
val counter = system.actorOf(Props[Counter], "counter")
counter ! Inc(20)
val counter = IORef(0)
...
counter.modify(_ + 20)
Killer Use Cases for Actors
1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
3. Persistence
class MyProcessor extends Processor {
def receive = {
case Persistent(payload, sequence) =>
doWork(payload, sequence)
case other =>
}
}
...
val processor =
actorOf(Props[MyProcessor],
name = "myProcessor")
processor ! Persistent("foo")
processor ! "bar"
val processor = payload =>
for {
sequence <- counter.modify(_ + 1)
_ <- persist(payload)
v <- doWork(payload, sequence)
} yield v
Killer Use Cases for Actors
1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
4. Distributed Compute
class SimpleClusterListener extends Actor with ActorLogging {
val cluster = Cluster(context.system)
// subscribe to cluster changes, re-subscribe when restart
override def preStart(): Unit = {
cluster.subscribe(self, initialStateMode = InitialStateAsEvents,
classOf[MemberEvent], classOf[UnreachableMember])
}
override def postStop(): Unit = cluster.unsubscribe(self)
def receive = {
case MemberUp(member) =>
log.info("Member is Up: {}", member.address)
case UnreachableMember(member) =>
log.info("Member detected as unreachable: {}", member)
case MemberRemoved(member, previousStatus) =>
log.info(
"Member is Removed: {} after {}",
member.address, previousStatus)
case _: MemberEvent => // ignore
}
}
¯_(ツ)_/¯
4. Distributed Compute
Killer Use Cases for Actors
1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
✓
PartialFunction[Any, Unit]
Can We Do Better?
Next-Generation Purely Functional Actor Design
A => B
Input Message Output Message
AKA “Function”
Next-Generation Purely Functional Actor Design
A => F[B]
Input Message Output Message
Effectful Actor
Output
Effect
Next-Generation Purely Functional Actor Design
G[A => F[B]]
Input Message Output Message
Effectfully-Created Effectful Actor
Output
Effect
Creation
Effect
Next-Generation Purely Functional Actor Design
def increment(n: Int): IO[Void, Int] = ???
Next-Generation Purely Functional Actor Design
def increment(n: Int): IO[Void, Int] =
for {
counter <- IORef(0)
value <- counter.modify(_ + n)
} yield value
Next-Generation Purely Functional Actor Design
val makeActor: IO[Void, Int => IO[Void, Int]] =
for {
counter <- IORef(0)
actor = (n: Int) => counter.modify(_ + n)
} yield actor
Next-Generation Purely Functional Actor Design
type Actor[E, I, O] = I => IO[E, O]
val makeActor: IO[Void, Actor[Void, Int, Int]] =
for {
counter <- IORef(0)
actor = (n: Int) => counter.modify(_ + n)
} yield actor
implicit class ActorSyntax[E, I, O](actor: Actor[E, I, O]) {
def ! (i: I): IO[E, O] = actor(i)
}
...
for {
v <- actor ! 20
} yield v
Next-Generation Purely Functional Actor Design
val makeActor: IO[Void, Actor[Void, Int, Int]] =
for {
counter <- IORef(0)
queue <- AsyncQueue.make[(Int, Promise[Void, Int])]
worker <- queue.take.flatMap(t =>
counter.modify(_ + t._1).flatMap(t._2.complete)).forever.fork
actor = (n: Int) =>
for {
promise <- Promise.make[Void, Int]
_ <- queue.offer((n, promise))
value <- promise.get
} yield value
} yield actor
Next-Generation Purely Functional Actor Design
type Actor[E, I, O] = I => IO[E, O]
def persistIn[E, I: EncodeJson, O](actor: Actor[E, I, O]): Actor[E, I, O]
def persistOut[E, I, O: EncodeJson](actor: Actor[E, I, O]): Actor[E, I, O]
def compose[E, I, O, U](l: Actor[E, I, O], r: Actor[E, O, U]): Actor[E, I, U]
...
Scalaz 8
1. Parallelism 2. Synchronization 3. Asynchronicity3. Signaling
Scalaz 8
Scalaz 8 Effect
✓ 195x faster*
✓ Type-safe
✓ Purely functional
✓ Resource-safe
✓ Compositional
Akka Future & Actors
❌ 195x slower*
❌ Type-unsafe
❌ Dysfunctional
❌ Resource-unsafe
❌ Compostable
*Up to, in some benchmarks.
Top Reasons to Choose Actors*
1. Your Code Is Way
Too Fast
2. Your Code Is Too
Composable
3. Your Code Is Too Easy to
Understand
*Actors are sometimes useful, like assembly language. But we can often do better.
Scalaz 8 vs Akka Actors
THANK YOU TO SCALAR & SOFTWAREMILL!
John A. De Goes
@jdegoes - http://degoes.net

More Related Content

What's hot

Post-Free: Life After Free Monads
Post-Free: Life After Free MonadsPost-Free: Life After Free Monads
Post-Free: Life After Free Monads
John De Goes
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
John De Goes
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 

What's hot (20)

Post-Free: Life After Free Monads
Post-Free: Life After Free MonadsPost-Free: Life After Free Monads
Post-Free: Life After Free Monads
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
 
Streams for (Co)Free!
Streams for (Co)Free!Streams for (Co)Free!
Streams for (Co)Free!
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Fiber supervision in ZIO
Fiber supervision in ZIOFiber supervision in ZIO
Fiber supervision in ZIO
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
Scalaz Stream: Rebirth
Scalaz Stream: RebirthScalaz Stream: Rebirth
Scalaz Stream: Rebirth
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Fun with Kotlin
Fun with KotlinFun with Kotlin
Fun with Kotlin
 
Zio from Home
Zio from Home Zio from Home
Zio from Home
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 

Similar to Scalaz 8 vs Akka Actors

Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Vaclav Pech
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
parag978978
 

Similar to Scalaz 8 vs Akka Actors (20)

Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Akka tips
Akka tipsAkka tips
Akka tips
 
Actor based approach in practice for Swift developers
Actor based approach in practice for Swift developersActor based approach in practice for Swift developers
Actor based approach in practice for Swift developers
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Akka
AkkaAkka
Akka
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applications
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
 
Akka knolx
Akka knolxAkka knolx
Akka knolx
 
Akka and futures
Akka and futuresAkka and futures
Akka and futures
 
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
 
Akka patterns
Akka patternsAkka patterns
Akka patterns
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka features
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
Futzing with actors (etc.)
Futzing with actors (etc.)Futzing with actors (etc.)
Futzing with actors (etc.)
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 

More from John De Goes

Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 

More from John De Goes (15)

Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIO
 
Scalaz Stream: Rebirth
Scalaz Stream: RebirthScalaz Stream: Rebirth
Scalaz Stream: Rebirth
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Getting Started with PureScript
Getting Started with PureScriptGetting Started with PureScript
Getting Started with PureScript
 
SlamData - How MongoDB Is Powering a Revolution in Visual Analytics
SlamData - How MongoDB Is Powering a Revolution in Visual AnalyticsSlamData - How MongoDB Is Powering a Revolution in Visual Analytics
SlamData - How MongoDB Is Powering a Revolution in Visual Analytics
 
The Next Great Functional Programming Language
The Next Great Functional Programming LanguageThe Next Great Functional Programming Language
The Next Great Functional Programming Language
 
The Dark Side of NoSQL
The Dark Side of NoSQLThe Dark Side of NoSQL
The Dark Side of NoSQL
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Quirrel & R for Dummies
Quirrel & R for DummiesQuirrel & R for Dummies
Quirrel & R for Dummies
 
In-Database Predictive Analytics
In-Database Predictive AnalyticsIn-Database Predictive Analytics
In-Database Predictive Analytics
 
Analytics Maturity Model
Analytics Maturity ModelAnalytics Maturity Model
Analytics Maturity Model
 
Rise of the scientific database
Rise of the scientific databaseRise of the scientific database
Rise of the scientific database
 
Fun with automata
Fun with automataFun with automata
Fun with automata
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Scalaz 8 vs Akka Actors

  • 1. Scalaz 8 vs Akka Actors Scalar 2018 - Warsaw, Poland John A. De Goes @jdegoes - http://degoes.net
  • 2. WARNING: The talk you are about to see was rejected from Scala Days 2018 due to extremely disturbing content. Attendee discretion is advised.
  • 3. Ultimate Question of Software Development
  • 4. Ultimate Question of Software Development How can we bend light so we can reactively build reactive microsystems that react to reacting reactivity???
  • 5. Answer to the Ultimate Question of Software Development PartialFunction[Any, Unit] Input Message AKA “Actor”
  • 6. Killer Use Cases for Actors 1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
  • 7. 1. Parallelism sealed trait Message case class Chunk(v: Array[Byte]) class ChunkActor extends Actor { def receive = { case Chunk(v) => sender ! encrypt(v) } } val chunkActors = context.actorOf(Props[ChunkActor]. withRouter(RoundRobinPool(4)), name = "ChunkActors") … chunks.foreach (chunk => chunkActors forward (Chunk(chunk))) IO.concurrently(chunks.map(encrypt(_)))
  • 8. Killer Use Cases for Actors 1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
  • 9. 2. Concurrent State sealed trait Message case object Get extends Message case class Inc(value: Int) extends Message class Counter extends Actor { var counter: Int = 0 def receive = { case Get => sender ! counter case Inc(v) => counter += v sender ! counter } } ... val system = ActorSystem("counter") val counter = system.actorOf(Props[Counter], "counter") counter ! Inc(20) val counter = IORef(0) ... counter.modify(_ + 20)
  • 10. Killer Use Cases for Actors 1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
  • 11. 3. Persistence class MyProcessor extends Processor { def receive = { case Persistent(payload, sequence) => doWork(payload, sequence) case other => } } ... val processor = actorOf(Props[MyProcessor], name = "myProcessor") processor ! Persistent("foo") processor ! "bar" val processor = payload => for { sequence <- counter.modify(_ + 1) _ <- persist(payload) v <- doWork(payload, sequence) } yield v
  • 12. Killer Use Cases for Actors 1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence
  • 13. 4. Distributed Compute class SimpleClusterListener extends Actor with ActorLogging { val cluster = Cluster(context.system) // subscribe to cluster changes, re-subscribe when restart override def preStart(): Unit = { cluster.subscribe(self, initialStateMode = InitialStateAsEvents, classOf[MemberEvent], classOf[UnreachableMember]) } override def postStop(): Unit = cluster.unsubscribe(self) def receive = { case MemberUp(member) => log.info("Member is Up: {}", member.address) case UnreachableMember(member) => log.info("Member detected as unreachable: {}", member) case MemberRemoved(member, previousStatus) => log.info( "Member is Removed: {} after {}", member.address, previousStatus) case _: MemberEvent => // ignore } } ¯_(ツ)_/¯
  • 15. Killer Use Cases for Actors 1. Parallelism 2. Concurrent State 3. Distributed Compute3. Persistence ✓
  • 17. Can We Do Better?
  • 18. Next-Generation Purely Functional Actor Design A => B Input Message Output Message AKA “Function”
  • 19. Next-Generation Purely Functional Actor Design A => F[B] Input Message Output Message Effectful Actor Output Effect
  • 20. Next-Generation Purely Functional Actor Design G[A => F[B]] Input Message Output Message Effectfully-Created Effectful Actor Output Effect Creation Effect
  • 21. Next-Generation Purely Functional Actor Design def increment(n: Int): IO[Void, Int] = ???
  • 22. Next-Generation Purely Functional Actor Design def increment(n: Int): IO[Void, Int] = for { counter <- IORef(0) value <- counter.modify(_ + n) } yield value
  • 23. Next-Generation Purely Functional Actor Design val makeActor: IO[Void, Int => IO[Void, Int]] = for { counter <- IORef(0) actor = (n: Int) => counter.modify(_ + n) } yield actor
  • 24. Next-Generation Purely Functional Actor Design type Actor[E, I, O] = I => IO[E, O] val makeActor: IO[Void, Actor[Void, Int, Int]] = for { counter <- IORef(0) actor = (n: Int) => counter.modify(_ + n) } yield actor implicit class ActorSyntax[E, I, O](actor: Actor[E, I, O]) { def ! (i: I): IO[E, O] = actor(i) } ... for { v <- actor ! 20 } yield v
  • 25. Next-Generation Purely Functional Actor Design val makeActor: IO[Void, Actor[Void, Int, Int]] = for { counter <- IORef(0) queue <- AsyncQueue.make[(Int, Promise[Void, Int])] worker <- queue.take.flatMap(t => counter.modify(_ + t._1).flatMap(t._2.complete)).forever.fork actor = (n: Int) => for { promise <- Promise.make[Void, Int] _ <- queue.offer((n, promise)) value <- promise.get } yield value } yield actor
  • 26. Next-Generation Purely Functional Actor Design type Actor[E, I, O] = I => IO[E, O] def persistIn[E, I: EncodeJson, O](actor: Actor[E, I, O]): Actor[E, I, O] def persistOut[E, I, O: EncodeJson](actor: Actor[E, I, O]): Actor[E, I, O] def compose[E, I, O, U](l: Actor[E, I, O], r: Actor[E, O, U]): Actor[E, I, U] ...
  • 27.
  • 28. Scalaz 8 1. Parallelism 2. Synchronization 3. Asynchronicity3. Signaling
  • 29. Scalaz 8 Scalaz 8 Effect ✓ 195x faster* ✓ Type-safe ✓ Purely functional ✓ Resource-safe ✓ Compositional Akka Future & Actors ❌ 195x slower* ❌ Type-unsafe ❌ Dysfunctional ❌ Resource-unsafe ❌ Compostable *Up to, in some benchmarks.
  • 30. Top Reasons to Choose Actors* 1. Your Code Is Way Too Fast 2. Your Code Is Too Composable 3. Your Code Is Too Easy to Understand *Actors are sometimes useful, like assembly language. But we can often do better.
  • 31. Scalaz 8 vs Akka Actors THANK YOU TO SCALAR & SOFTWAREMILL! John A. De Goes @jdegoes - http://degoes.net