SlideShare a Scribd company logo
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?

More Related Content

What's hot

Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
Maneesh Chaturvedi
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
Maneesh Chaturvedi
 
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++
Functions in c++Functions in c++
Functions in c++
Rokonuzzaman Rony
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
Faizan Janjua
 
Inline functions
Inline functionsInline functions
Inline functions
DhwaniHingorani
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
Kumar
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
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 Programming
newmedio
 
Inline and lambda function
Inline and lambda functionInline and lambda function
Inline and lambda function
Jawad Khan
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Abdullah Turkistani
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadng
preethalal
 
Inline function(oops)
Inline function(oops)Inline function(oops)
Inline function(oops)
Jay Patel
 
C++ Function
C++ FunctionC++ Function
C++ Function
PingLun Liao
 
Function Parameters
Function ParametersFunction Parameters
Function Parameters
primeteacher32
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macros
Anand Kumar
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
C++ functions
C++ functionsC++ functions
C++ functions
Dawood Jutt
 

What's hot (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
 

Similar to Beyond Mere Actors

Pure Future
Pure FuturePure Future
Pure Future
Wiem Zine Elabidine
 
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
Raúl Raja Martínez
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
David Atchley
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Using Akka Futures
Using Akka FuturesUsing Akka Futures
Using Akka Futures
Knoldus Inc.
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
Knoldus 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 3
Philip Schwarz
 
Demystifying Eta Expansion
Demystifying Eta ExpansionDemystifying Eta Expansion
Demystifying Eta Expansion
Knoldus Inc.
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
Chris
 
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
Kurmendra Singh
 
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
amanabr
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
Knoldus Inc.
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
Oliver Daff
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
Angelo Corsaro
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Will Livengood
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
Devnology
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
Angelo Corsaro
 
Java 8
Java 8Java 8
Java 8
vilniusjug
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Ashita Agrawal
 

Similar to 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
 

Recently uploaded

Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 

Recently uploaded (20)

Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 

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.