SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
Beyond Mere Actors

  Concurrent Functional
 Programming with Scalaz

    Rúnar Bjarnason
Traditional Java Concurrency

  Manual creation of threads
  Manual synchronisation
  One thread per process
  Processes communicate by shared mutable state
Traditional Java Concurrency

  Manual creation of threads
  Manual synchronisation
  One thread per process
  Processes communicate by shared mutable state
  Problem: Threads do not compose
java.util.concurrent

Since JDK 5

Includes useful building blocks for making higher-level
abstractions.
Atomic references
Countdown latches
ExecutorService
Callable
Future
Futures

Provided by java.util.concurrent.Future

Future[A] represents a computation of type A, executing
concurrently.

Future.get: A
Futures

ExecutorService is a means of turning Callable[A] into Future
[A]
implicit def toCallable[A](a: => A) =
   new Callable[A] { def call = a }
implicit val s = Executors.newCachedThreadPool

e1 and e2 are evaluated concurrently
val x = s submit { e1 }
val y = e2

Futures can participate in expressions:
val z = f(x.get, y)

No mention of threads in this code. No shared state.
Futures

There's a serious problem. How would we implement this
function?

def fmap[A,B](fu: Future[A], f: A => B)
  (implicit s: ExecutorService):Future[B] =
Futures

We have to call Future.get, blocking the thread.

def fmap[A,B](fu: Future[A], f: A => B)
  (implicit s: ExecutorService):Future[B] =
    s submit f(fu.get)

This is a barrier to composition.

Futures cannot be composed without blocking a thread.
scalaz.concurrent

Strategy - Abstracts over ways of evaluating expressions
concurrently.

Actor - Light-weight thread-like process, communicates by
asynchronous messaging.

Promise - Compose concurrent functions.
Parallel Strategies

ExecutorService: Callable[A] => Future[A]

Callable[A] ~= Function0[A]
Future[A] ~= Function0[A]
Also written: () => A

Strategy[A] ~= Function0[A] => Function0[A]
Also written: (() => A) => () => A

Turns a lazy expression of type A into an expression of the
same type.
scalaz.concurrent.Strategy

Separates the concerns of parallelism and algorithm.
Captures some threading pattern and isolates the rest of your
code from threading.

Executor - wraps the expression in a Callable, turns it into a
Future via an implicit ExecutorService.

Naive - Starts a new thread for each expression.

Sequential - Evaluates each expression in the current thread
(no concurrency).

Identity - Performs no evaluation at all.
Parallel Strategies

You can write your own Strategies.

Some (crazy) ideas:
  Delegate to the fork/join scheduler.
  Run in the Swing thread.
  Call a remote machine.
  Ask a human, or produce a random result.
Actors

Provide asynchronous communication among processes.

Processes receive messages on a queue.

Messages can be enqueued with no waiting.

An actor is always either suspended (waiting for messages) or
working (acting on a message).

An actor processes messages in some (but any) order.
scalaz.concurrent.Actor

These are not scala.actors. Differences:
   Simpler. Scalaz Actors are distilled to the essentials.
   Messages are typed.

Actor is sealed, and instantiated by supplying:
   type A
   effect: A => Unit
   (implicit) strategy: Strategy[Unit]
   (Optional) Error Handler: Throwable => Unit
Strategy + Effect = Actor
Actor Example
Actor: Contravariant Cofunctor

An actor can be composed with a function:
    x.comap(f)

Comap has this type:
   comap: (B => A) => Actor[A] => Actor[B]

Returns a new actor that applies f to its messages and sends
the result to actor x.

x comap f is equivalent to x compose f, but results in an
Actor, as opposed to a function.
Problems with Actors
Problems with Actors

   You have to think about state and process communication.
   An actor can (must?) expose its state.
   It's all about side-effects!

Side-effects absolutely do not compose.
You cannot compose Actors with each other.

Actor[A] ~= (A => Unit)

There's not a lot you can do with Unit.
scalaz.concurrent.Promise

Similar to Future, but non-blocking.

Implements map and flatMap without calling get.
scalaz.concurrent.Promise

Constructed by giving an expression to promise:

lazy val e:String = {Thread sleep 5000; "Hi."}
val p: Promise[String] = promise(e)

Takes an implicit Strategy[Unit]. The expression is
evaluated concurrently by the Strategy.
Think of this as forking a process.

The result is available later by calling p.get. This blocks the
current thread.

But we never have to call it!
On Time-Travel

Promised values are available in the future.

What does it mean to get a value out of the future?
Time-travel into the future is easy. Just wait.
But we don't have to go into the future.
We can give our future-selves instructions.

Instead of getting values out of the future, we send
computations into the future.
Lifting a function into the future

Consider: promise(e).map(f)

map has the following type:
(A => B) => Promise[A] => Promise[B]

We take an ordinary function and turn it into a function that
operates on Promises.

It's saying: Evaluate e concurrently, applying f to the result
when it's ready. Returns a Promise of the final result.
Composing concurrent functions

A concurrent function is of the type A => Promise[B]

Syntax sugar to make any function a concurrent function:
val g = f.promise
promise(f: A => B) = (a:A) => promise(f(a))

We can bind the arguments of concurrent functions to promised
values, using flatMap:
promise(e).flatMap(g)

flatMap has this type:
(A => Promise[B]) => Promise[A] => Promise[B]
Composing concurrent functions

We can compose concurrent functions with each other too.

If f: A => Promise[B] and g: B => Promise[C] then
(f >=> g): A => Promise[C]

(f >=> g)(x) is equivalent to f(x) flatMap g
Joining Promises

join[A]: Promise[Promise[A]] => Promise[A]

(promise { promise { expression } }).join

Join removes the "inner brackets".

A process that forks other processes can join with them later,
without synchronizing or blocking.
A process whose result depends on child processes is still just
a single Promise, and thus can run in a single thread.

Therefore, pure promises cannot deadlock or starve.
Promises - Example
But wait, there's more!

Parallel counterparts of map, flatMap, and zipWith:
parMap, parFlatMap, and parZipWith

x.parMap(f)

Where x can be a List, Stream, Function, Option, Promise, etc.
Scalaz provides parMap on any Functor.

parZipWith for parallel zipping of any Applicative Functor.

parFlatMap is provided for any Monad.
Advanced Topics

If you understand Promise, then you understand monads.
Advanced Topics

Functor is simply this interface:

trait Functor[F[_]] {
  def fmap[A, B](r: F[A], f: A => B): F[B]
}

Functors are "mappable". Any implementation of this interface
is a functor. Here's the Promise functor:
new Functor[Promise] {
   def fmap[A, B](t: Promise[A], f: A => B) =
       t.flatMap(a => promise(f(a)))
}
Advanced Topics

Monad is simply this interface:
trait Monad[M[_]] extends Functor[M] {
  fork[A](a: A): M[A]
  join[A](a: M[M[A]]): M[A]
}

Monads are fork/map/joinable. Any implementation of this
interface is a monad. Here's the Promise monad:
new Monad[Promise] {
   def fork[A](a: A) = promise(a)
   def join[A](a: Promise[Promise[A]]) =
      a.flatMap(Functions.identity)
}
Welcome to Scalaz

Scalaz is a general-purpose library for higher-order
programming.

There's a lot here. Go play around, and ask questions on the
Scalaz Google Group.

For more information:
http://code.google.com/p/scalaz

Documentation is lacking, but we're working on that.

A release of Scalaz 5.0 will coincide with a release of Scala
2.8.
Questions?

Contenu connexe

Tendances

Functions in c++
Functions in c++Functions in c++
Functions in c++Maaz Hasan
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Jenish Patel
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)Faizan Janjua
 
Function class in c++
Function class in c++Function class in c++
Function class in c++Kumar
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programmingnewmedio
 
Inline and lambda function
Inline and lambda functionInline and lambda function
Inline and lambda functionJawad Khan
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadngpreethalal
 
Inline function(oops)
Inline function(oops)Inline function(oops)
Inline function(oops)Jay Patel
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macrosAnand Kumar
 

Tendances (20)

Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
 
Inline functions
Inline functionsInline functions
Inline functions
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Inline and lambda function
Inline and lambda functionInline and lambda function
Inline and lambda function
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadng
 
Inline function(oops)
Inline function(oops)Inline function(oops)
Inline function(oops)
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Function Parameters
Function ParametersFunction Parameters
Function Parameters
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macros
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
C++ functions
C++ functionsC++ functions
C++ functions
 

Similaire à Beyond Mere Actors

Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursionDavid Atchley
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Using Akka Futures
Using Akka FuturesUsing Akka Futures
Using Akka FuturesKnoldus Inc.
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka RemotingKnoldus Inc.
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Philip Schwarz
 
Demystifying Eta Expansion
Demystifying Eta ExpansionDemystifying Eta Expansion
Demystifying Eta ExpansionKnoldus Inc.
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersChris
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013amanabr
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Kurmendra Singh
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus Inc.
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture FourAngelo Corsaro
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScriptWill Livengood
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 

Similaire à Beyond Mere Actors (20)

Pure Future
Pure FuturePure Future
Pure Future
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic Programmer
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Using Akka Futures
Using Akka FuturesUsing Akka Futures
Using Akka Futures
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
Demystifying Eta Expansion
Demystifying Eta ExpansionDemystifying Eta Expansion
Demystifying Eta Expansion
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Java 8
Java 8Java 8
Java 8
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Dernier

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 

Dernier (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Beyond Mere Actors

  • 1. Beyond Mere Actors Concurrent Functional Programming with Scalaz Rúnar Bjarnason
  • 2. Traditional Java Concurrency Manual creation of threads Manual synchronisation One thread per process Processes communicate by shared mutable state
  • 3. Traditional Java Concurrency Manual creation of threads Manual synchronisation One thread per process Processes communicate by shared mutable state Problem: Threads do not compose
  • 4. java.util.concurrent Since JDK 5 Includes useful building blocks for making higher-level abstractions. Atomic references Countdown latches ExecutorService Callable Future
  • 5. Futures Provided by java.util.concurrent.Future Future[A] represents a computation of type A, executing concurrently. Future.get: A
  • 6. Futures ExecutorService is a means of turning Callable[A] into Future [A] implicit def toCallable[A](a: => A) = new Callable[A] { def call = a } implicit val s = Executors.newCachedThreadPool e1 and e2 are evaluated concurrently val x = s submit { e1 } val y = e2 Futures can participate in expressions: val z = f(x.get, y) No mention of threads in this code. No shared state.
  • 7. Futures There's a serious problem. How would we implement this function? def fmap[A,B](fu: Future[A], f: A => B) (implicit s: ExecutorService):Future[B] =
  • 8. Futures We have to call Future.get, blocking the thread. def fmap[A,B](fu: Future[A], f: A => B) (implicit s: ExecutorService):Future[B] = s submit f(fu.get) This is a barrier to composition. Futures cannot be composed without blocking a thread.
  • 9. scalaz.concurrent Strategy - Abstracts over ways of evaluating expressions concurrently. Actor - Light-weight thread-like process, communicates by asynchronous messaging. Promise - Compose concurrent functions.
  • 10. Parallel Strategies ExecutorService: Callable[A] => Future[A] Callable[A] ~= Function0[A] Future[A] ~= Function0[A] Also written: () => A Strategy[A] ~= Function0[A] => Function0[A] Also written: (() => A) => () => A Turns a lazy expression of type A into an expression of the same type.
  • 11. scalaz.concurrent.Strategy Separates the concerns of parallelism and algorithm. Captures some threading pattern and isolates the rest of your code from threading. Executor - wraps the expression in a Callable, turns it into a Future via an implicit ExecutorService. Naive - Starts a new thread for each expression. Sequential - Evaluates each expression in the current thread (no concurrency). Identity - Performs no evaluation at all.
  • 12. Parallel Strategies You can write your own Strategies. Some (crazy) ideas: Delegate to the fork/join scheduler. Run in the Swing thread. Call a remote machine. Ask a human, or produce a random result.
  • 13. Actors Provide asynchronous communication among processes. Processes receive messages on a queue. Messages can be enqueued with no waiting. An actor is always either suspended (waiting for messages) or working (acting on a message). An actor processes messages in some (but any) order.
  • 14. scalaz.concurrent.Actor These are not scala.actors. Differences: Simpler. Scalaz Actors are distilled to the essentials. Messages are typed. Actor is sealed, and instantiated by supplying: type A effect: A => Unit (implicit) strategy: Strategy[Unit] (Optional) Error Handler: Throwable => Unit Strategy + Effect = Actor
  • 16. Actor: Contravariant Cofunctor An actor can be composed with a function: x.comap(f) Comap has this type: comap: (B => A) => Actor[A] => Actor[B] Returns a new actor that applies f to its messages and sends the result to actor x. x comap f is equivalent to x compose f, but results in an Actor, as opposed to a function.
  • 18. Problems with Actors You have to think about state and process communication. An actor can (must?) expose its state. It's all about side-effects! Side-effects absolutely do not compose. You cannot compose Actors with each other. Actor[A] ~= (A => Unit) There's not a lot you can do with Unit.
  • 19. scalaz.concurrent.Promise Similar to Future, but non-blocking. Implements map and flatMap without calling get.
  • 20. scalaz.concurrent.Promise Constructed by giving an expression to promise: lazy val e:String = {Thread sleep 5000; "Hi."} val p: Promise[String] = promise(e) Takes an implicit Strategy[Unit]. The expression is evaluated concurrently by the Strategy. Think of this as forking a process. The result is available later by calling p.get. This blocks the current thread. But we never have to call it!
  • 21. On Time-Travel Promised values are available in the future. What does it mean to get a value out of the future? Time-travel into the future is easy. Just wait. But we don't have to go into the future. We can give our future-selves instructions. Instead of getting values out of the future, we send computations into the future.
  • 22. Lifting a function into the future Consider: promise(e).map(f) map has the following type: (A => B) => Promise[A] => Promise[B] We take an ordinary function and turn it into a function that operates on Promises. It's saying: Evaluate e concurrently, applying f to the result when it's ready. Returns a Promise of the final result.
  • 23. Composing concurrent functions A concurrent function is of the type A => Promise[B] Syntax sugar to make any function a concurrent function: val g = f.promise promise(f: A => B) = (a:A) => promise(f(a)) We can bind the arguments of concurrent functions to promised values, using flatMap: promise(e).flatMap(g) flatMap has this type: (A => Promise[B]) => Promise[A] => Promise[B]
  • 24. Composing concurrent functions We can compose concurrent functions with each other too. If f: A => Promise[B] and g: B => Promise[C] then (f >=> g): A => Promise[C] (f >=> g)(x) is equivalent to f(x) flatMap g
  • 25. Joining Promises join[A]: Promise[Promise[A]] => Promise[A] (promise { promise { expression } }).join Join removes the "inner brackets". A process that forks other processes can join with them later, without synchronizing or blocking. A process whose result depends on child processes is still just a single Promise, and thus can run in a single thread. Therefore, pure promises cannot deadlock or starve.
  • 27. But wait, there's more! Parallel counterparts of map, flatMap, and zipWith: parMap, parFlatMap, and parZipWith x.parMap(f) Where x can be a List, Stream, Function, Option, Promise, etc. Scalaz provides parMap on any Functor. parZipWith for parallel zipping of any Applicative Functor. parFlatMap is provided for any Monad.
  • 28. Advanced Topics If you understand Promise, then you understand monads.
  • 29. Advanced Topics Functor is simply this interface: trait Functor[F[_]] { def fmap[A, B](r: F[A], f: A => B): F[B] } Functors are "mappable". Any implementation of this interface is a functor. Here's the Promise functor: new Functor[Promise] { def fmap[A, B](t: Promise[A], f: A => B) = t.flatMap(a => promise(f(a))) }
  • 30. Advanced Topics Monad is simply this interface: trait Monad[M[_]] extends Functor[M] { fork[A](a: A): M[A] join[A](a: M[M[A]]): M[A] } Monads are fork/map/joinable. Any implementation of this interface is a monad. Here's the Promise monad: new Monad[Promise] { def fork[A](a: A) = promise(a) def join[A](a: Promise[Promise[A]]) = a.flatMap(Functions.identity) }
  • 31. Welcome to Scalaz Scalaz is a general-purpose library for higher-order programming. There's a lot here. Go play around, and ask questions on the Scalaz Google Group. For more information: http://code.google.com/p/scalaz Documentation is lacking, but we're working on that. A release of Scalaz 5.0 will coincide with a release of Scala 2.8.