SlideShare a Scribd company logo
1 of 59
Download to read offline
Pure Future
Wiem Zine Elabidine
Krakow Scala User Group
HELLO!
I am Wiem
Scala Backend Engineer at MOIA
@WiemZin
@wi101
2
Plan
Parallelism
Vs
Concurrency
Thread
Vs
Callable
Pure Future
3
Plan
Parallelism
vs
Concurrency
Runnable
vs
Callable
vs
Future
Pure Future
4
5
Place your screenshot here
Parallelism vs Concurrency
6
7
Parallelism vs Concurrency
Runtime.getRuntime.availableProcessors()
Parallelism is the simultaneous
execution of multiple things using
the capability of the multi-core
hardware.
8
Place your screenshot here
Parallelism
Image from: https://computing.llnl.gov/tutorials/parallel_comp/
Parallelism vs Concurrency
Concurrency is the ability for many tasks to be
executed out-of-order and coordinate the
result.
9
Parallelism vs Concurrency
10
Place your screenshot here
Concurrency
Image from: http://adit.io/posts/2013-05-11-The-Dining-Philosophers-Problem-With-Ron-Swanson.html
Parallelism vs Concurrency
Concurrency
- Dealing with MANY
things at ONCE
- Structure
- Communication with
independent
components and
coordinating with them
Parallelism
- Doing MANY things at
ONCE
- Execution
- Executing simultaneous
processes
11
Parallelism vs ConcurrencyParallelism vs Concurrency
Summary
Runnable vs Callable vs Future
12
Define parallel tasks
Thread
✘ Thread is a linear flow of execution
✘ Managed by a Scheduler
13
Runnable vs Callable vs Future
Thread
✘ Thread is a linear flow of execution
✘ Managed by a Scheduler
14
Runnable vs Callable vs Future
def task() =
new Thread(() =>
println(s"Hi Thread: ${Thread.currentThread.getName}"))
task().start()
Thread
✘ Thread is a linear flow of execution
✘ Managed by a Scheduler
15
Runnable vs Callable vs Future
def task() =
new Thread(() =>
println(s"Hi Thread: ${Thread.currentThread.getName}"))
task().start()
✘ 1 Thread = 1 OS Thread
Thread pool Execution
✘ Uses blocking queue
16
Runnable vs Callable vs Future
Execution Service
17
Runnable vs Callable vs Future
class ExecutorService {
def submit(a: Runnable): Future[Unit]
def submit[A](a: Callable[A]): Future[A]
}
val service: ExecutorService =
Executors.newFixedThreadPool(2)
Execution Service
18
Runnable vs Callable vs Future
class ExecutorService {
def submit(a: Runnable): Future[Unit]
def submit[A](a: Callable[A]): Future[A]
}
val service: ExecutorService =
Executors.newFixedThreadPool(2)
Execution Service
19
Runnable vs Callable vs Future
class ExecutorService {
def submit(a: Runnable): Future[Unit]
def submit[A](a: Callable[A]): Future[A]
}
val service: ExecutorService =
Executors.newFixedThreadPool(2)
Runnable
20
Runnable vs Callable vs Future
trait Runnable {
def run: Unit
}
Runnable
✘ Define tasks that extend Runnable
21
Runnable vs Callable vs Future
Runnable
✘ Define tasks that extend Runnable
22
Runnable vs Callable vs Future
val t1 = task()
val t2 = task()
val t3 = task()
Runnable
✘ Define tasks that extend Runnable
✘ Submit the parallel tasks
23
Runnable vs Callable vs Future
service.submit(t1)
service.submit(t2)
service.submit(t3)
Runnable
✘ Define tasks that extend Runnable
✘ Submit the parallel tasks
24
Runnable vs Callable vs Future
How could we get meaningful values from the
separate Threads?
Runnable
25
Runnable vs Callable vs Future
trait Runnable { def run: Unit }
✘ Define tasks that extend Runnable
✘ Submit the parallel tasks
How could we get meaningful values from the
separate Threads?
Runnable
26
Runnable vs Callable vs Future
class ExecutorService {
def submit(a: Runnable): Future[Unit]
def submit[A](a: Callable[A]): Future[A]
}
Runnable
27
Runnable vs Callable vs Future
class ExecutorService {
def submit(a: Runnable): Future[Unit]
def submit[A](a: Callable[A]): Future[A]
}
Callable
28
Runnable vs Callable vs Future
trait Callable[A] {
def call: A
}
Callable
✘ Define tasks that extend Callable
29
Runnable vs Callable vs Future
def increment(i: Int) =
new Callable[Int] {
def call(): Int = i +1
}
Callable
✘ Define tasks that extend Callable
✘ Submit the parallel tasks
30
Runnable vs Callable vs Future
import java.util.concurrent.Future
val v1: Future[Int] = service.submit(increment(1))
val v2: Future[Int] = service.submit(increment(2))
Callable
✘ Define tasks that extend Callable
✘ Submit the parallel tasks
31
Runnable vs Callable vs Future
import java.util.concurrent.Future
val v1: Future[Int] = service.submit(increment(1))
val v2: Future[Int] = service.submit(increment(2))
How could we use the value of every Future?
Callable
✘ Define tasks that extend Callable
✘ Submit the parallel tasks
32
Runnable vs Callable vs Future
import java.util.concurrent.Future
val v1: Future[Int] = service.submit(increment(1))
val v2: Future[Int] = service.submit(increment(2))
How could we use the value of every Future?
trait Future[A] { def get: A }
Callable
✘ Define tasks that extend Callable
✘ Submit the parallel tasks
33
Runnable vs Callable vs Future
import java.util.concurrent.Future
val v1: Future[Int] = service.submit(increment(1))
val v2: Future[Int] = service.submit(increment(2))
STATEMENTS
✘ Define futures
Future
34
Runnable vs Callable vs Future
def increment(i: Int) = Future.successful(i + 1)
val f1: Future[Int] = increment(1)
val f2: Future[Int] = increment(2)
val result: Future[Int] = for {
v1 <- f1
v2 <- f2
} yield v1 + v2
✘ Define futures
Future
35
Runnable vs Callable vs Future
def increment(i: Int) = Future.successful(i + 1)
val f1: Future[Int] = increment(1)
val f2: Future[Int] = increment(2)
val result: Future[Int] = for {
v1 <- f1
v2 <- f2
} yield v1 + v2
Cannot find an implicit ExecutionContext. You might pass
[error] an (implicit ec: ExecutionContext) parameter to your method
[error] or import scala.concurrent.ExecutionContext.Implicits.global.
[error] v2 <- f2
[error] ^
✘ Define futures
Future
36
Runnable vs Callable vs Future
import scala.concurrent.ExecutionContext.Implicits.global
def increment(i: Int) = Future.successful(i + 1)
val f1: Future[Int] = increment(1)
val f2: Future[Int] = increment(2)
val result: Future[Int] = for {
v1 <- f1
v2 <- f2
} yield v1 + v2
37
Pure Future
38
Future
Pure Future
✘ Asynchronous
✘ Resumes when the value is ready!
39
Future
Pure Future
✘ Asynchronous
✘ Resumes when the value is ready!
trait Future[A] {
def apply(cb: A => Unit): Unit
}
40
Future
Pure Future
✘ Asynchronous
✘ Resumes when the value is ready!
trait Future[A] {
private[api] def apply(cb: A => Unit): Unit
}
41
The Data Type for parallel computations
Pure Future
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
42
The Data Type for parallel computations
Pure Future
type Par[A] = ExecutorService => Future[A]
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
43
The Data Type for parallel computations
Pure Future
type Par[A] = ExecutorService => Future[A]
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
44
The Data Type for parallel computations
Pure Future
type Par[A] = ExecutorService => Future[A]
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
45
The Data Type for parallel computations
Pure Future
object Par {
def unit[A](a: A): Par[A] = ???
}
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
46
Par.unit
Pure Future
type Par[A] = ExecutorService => Future[A]
object Par {
def unit[A](a: A): Par[A] = (_: ExecutorService) =>
new Future[A] {
def apply(cb: A => Unit): Unit = cb(a)
}
}
47
The Data Type for parallel computations
Pure Future
object Par {
def fork[A](a: Par[A]): Par[A] = ???
}
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
48
Par.fork
Pure Future
type Par[A] = ExecutorService => Future[A]
object Par {
def fork[A](a: Par[A]): Par[A] = es =>
new Future[A] {
def apply(cb: A => Unit): Unit =
es.submit(new Callable[Unit] {
def call: Unit = a(es)(cb) // a(es).apply(cb)
})
}
}
49
The Data Type for parallel computations
Pure Future
object Par {
def run[A](es: ExecutorService)(par: Par[A]): A =
???
}
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
50
Par.run
Pure Future
type Par[A] = ExecutorService => Future[A]
object Par {
def run[A](es: ExecutorService)(p: Par[A]): A = {
val ref = new AtomicReference[A]
val latch = new CountDownLatch(1)
p(es) { a =>
ref.set(a)
latch.countDown()
}
latch.await()
ref.get
}
}
51
Par.run
Pure Future
type Par[A] = ExecutorService => Future[A]
object Par {
def run[A](es: ExecutorService)(p: Par[A]): A = {
val ref = new AtomicReference[A]
val latch = new CountDownLatch(1)
p(es) { a =>
ref.set(a)
latch.countDown()
}
latch.await()
ref.get
}
}
val one = Par.unit(1)
run(es)(one) ⇒ 1
“Programming with mutability is
like working with the
mother-in-law who’s waiting you to
fail” - Venkat Subramaniam
52
object Par {
def map[A, B](a: Par[A])(f: A => B): Par[B]
def flatMap[A, B](a: Par[A])(f: A => Par[B]): Par[B]
def parMap[A, B](l: List[A])(f: A => B): Par[List[B]]
def map2[A, B, C](a: Par[A], b: Par[B])(f: (A, B) => C): Par[C]
...
}
53
The Data Type for parallel computations
Pure Future
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
54
The Data Type for parallel computations
Pure Future
✘ Requires ExecutorService
✘ Asynchronously performs a given computation of any type
✘ Contains a result of the computation
✘ Composable
object Par {
def map[A, B](a: Par[A])(f: A => B): Par[B]
def flatMap[A, B](a: Par[A])(f: A => Par[B]): Par[B]
def parMap[A, B](l: List[A])(f: A => B): Par[List[B]]
def map2[A, B, C](a: Par[A], b: Par[B])(f: (A, B) => C): Par[C]
...
}
Example
Pure Future
1 2 3 4 5 6 7 8 9
56
Example
Pure Future
1 2 3 4 5 6 7 8 9
def sum(ints: IndexedSeq[Int]): Par[Int] =
if (ints.size <= 1) Par.unit(ints.headOption getOrElse 0)
else {
val (l, r) = ints.splitAt(ints.size / 2)
Par.fork(Par.map2(sum(l), sum(r))(_ + _))
}
FP Scala libraries
ZIO: zio.dev
Cats-effect: typelevel.org/cats-effect
Monix: monix.io
57
Pure Future
References
✘ Functional programming in Scala Book
✘ https://medium.com/@wiemzin/purely-functional-parallelism-in-scala-37ecb1e9999
✘ https://github.com/fpinscala/fpinscala/blob/master/answers/src/main/scala/fpinscala/paralle
lism/Nonblocking.scala
58
THANKS!
You can find me at
@WiemZin
@wi101
59

More Related Content

What's hot

Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }John De Goes
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsJohn De Goes
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsGlobalLogic Ukraine
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Ignacio Martín
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React AlicanteIgnacio Martín
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friendThe Software House
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga beginsDaniel Franz
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
 
Property-Based Testing
Property-Based TestingProperty-Based Testing
Property-Based TestingShai Geva
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Ruslan Shevchenko
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
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) Datagreenwop
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concernssaintiss
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FPLuka Jacobowitz
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 

What's hot (20)

Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friend
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Property-Based Testing
Property-Based TestingProperty-Based Testing
Property-Based Testing
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
 
Svitla talks 2021_03_25
Svitla talks 2021_03_25Svitla talks 2021_03_25
Svitla talks 2021_03_25
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
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
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concerns
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 

Similar to Pure Future

Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus Inc.
 
cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019Daniel Pfeiffer
 
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
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka RemotingKnoldus Inc.
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsDhivyaSubramaniyam
 
Monix : A Birds’ eye view
Monix : A Birds’ eye viewMonix : A Birds’ eye view
Monix : A Birds’ eye viewKnoldus Inc.
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play appsYevgeniy Brikman
 
What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13Paulo Morgado
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Paulo morgado what's new in c# 5.0
Paulo morgado   what's new in c# 5.0Paulo morgado   what's new in c# 5.0
Paulo morgado what's new in c# 5.0iseltech
 
Dependency injection with Scala
Dependency injection with ScalaDependency injection with Scala
Dependency injection with Scalasaar wexler
 

Similar to Pure Future (20)

Beyond Mere Actors
Beyond Mere ActorsBeyond Mere Actors
Beyond Mere Actors
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019
 
Thinking in Functions
Thinking in FunctionsThinking in Functions
Thinking in Functions
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
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
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
05 operators
05   operators05   operators
05 operators
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Monix : A Birds’ eye view
Monix : A Birds’ eye viewMonix : A Birds’ eye view
Monix : A Birds’ eye view
 
Monadologie
MonadologieMonadologie
Monadologie
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Paulo morgado what's new in c# 5.0
Paulo morgado   what's new in c# 5.0Paulo morgado   what's new in c# 5.0
Paulo morgado what's new in c# 5.0
 
Dependency injection with Scala
Dependency injection with ScalaDependency injection with Scala
Dependency injection with Scala
 

Recently uploaded

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 

Recently uploaded (20)

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 

Pure Future

  • 1. Pure Future Wiem Zine Elabidine Krakow Scala User Group
  • 2. HELLO! I am Wiem Scala Backend Engineer at MOIA @WiemZin @wi101 2
  • 7. 7 Parallelism vs Concurrency Runtime.getRuntime.availableProcessors() Parallelism is the simultaneous execution of multiple things using the capability of the multi-core hardware.
  • 8. 8 Place your screenshot here Parallelism Image from: https://computing.llnl.gov/tutorials/parallel_comp/ Parallelism vs Concurrency
  • 9. Concurrency is the ability for many tasks to be executed out-of-order and coordinate the result. 9 Parallelism vs Concurrency
  • 10. 10 Place your screenshot here Concurrency Image from: http://adit.io/posts/2013-05-11-The-Dining-Philosophers-Problem-With-Ron-Swanson.html Parallelism vs Concurrency
  • 11. Concurrency - Dealing with MANY things at ONCE - Structure - Communication with independent components and coordinating with them Parallelism - Doing MANY things at ONCE - Execution - Executing simultaneous processes 11 Parallelism vs ConcurrencyParallelism vs Concurrency Summary
  • 12. Runnable vs Callable vs Future 12 Define parallel tasks
  • 13. Thread ✘ Thread is a linear flow of execution ✘ Managed by a Scheduler 13 Runnable vs Callable vs Future
  • 14. Thread ✘ Thread is a linear flow of execution ✘ Managed by a Scheduler 14 Runnable vs Callable vs Future def task() = new Thread(() => println(s"Hi Thread: ${Thread.currentThread.getName}")) task().start()
  • 15. Thread ✘ Thread is a linear flow of execution ✘ Managed by a Scheduler 15 Runnable vs Callable vs Future def task() = new Thread(() => println(s"Hi Thread: ${Thread.currentThread.getName}")) task().start() ✘ 1 Thread = 1 OS Thread
  • 16. Thread pool Execution ✘ Uses blocking queue 16 Runnable vs Callable vs Future
  • 17. Execution Service 17 Runnable vs Callable vs Future class ExecutorService { def submit(a: Runnable): Future[Unit] def submit[A](a: Callable[A]): Future[A] } val service: ExecutorService = Executors.newFixedThreadPool(2)
  • 18. Execution Service 18 Runnable vs Callable vs Future class ExecutorService { def submit(a: Runnable): Future[Unit] def submit[A](a: Callable[A]): Future[A] } val service: ExecutorService = Executors.newFixedThreadPool(2)
  • 19. Execution Service 19 Runnable vs Callable vs Future class ExecutorService { def submit(a: Runnable): Future[Unit] def submit[A](a: Callable[A]): Future[A] } val service: ExecutorService = Executors.newFixedThreadPool(2)
  • 20. Runnable 20 Runnable vs Callable vs Future trait Runnable { def run: Unit }
  • 21. Runnable ✘ Define tasks that extend Runnable 21 Runnable vs Callable vs Future
  • 22. Runnable ✘ Define tasks that extend Runnable 22 Runnable vs Callable vs Future val t1 = task() val t2 = task() val t3 = task()
  • 23. Runnable ✘ Define tasks that extend Runnable ✘ Submit the parallel tasks 23 Runnable vs Callable vs Future service.submit(t1) service.submit(t2) service.submit(t3)
  • 24. Runnable ✘ Define tasks that extend Runnable ✘ Submit the parallel tasks 24 Runnable vs Callable vs Future How could we get meaningful values from the separate Threads?
  • 25. Runnable 25 Runnable vs Callable vs Future trait Runnable { def run: Unit } ✘ Define tasks that extend Runnable ✘ Submit the parallel tasks How could we get meaningful values from the separate Threads?
  • 26. Runnable 26 Runnable vs Callable vs Future class ExecutorService { def submit(a: Runnable): Future[Unit] def submit[A](a: Callable[A]): Future[A] }
  • 27. Runnable 27 Runnable vs Callable vs Future class ExecutorService { def submit(a: Runnable): Future[Unit] def submit[A](a: Callable[A]): Future[A] }
  • 28. Callable 28 Runnable vs Callable vs Future trait Callable[A] { def call: A }
  • 29. Callable ✘ Define tasks that extend Callable 29 Runnable vs Callable vs Future def increment(i: Int) = new Callable[Int] { def call(): Int = i +1 }
  • 30. Callable ✘ Define tasks that extend Callable ✘ Submit the parallel tasks 30 Runnable vs Callable vs Future import java.util.concurrent.Future val v1: Future[Int] = service.submit(increment(1)) val v2: Future[Int] = service.submit(increment(2))
  • 31. Callable ✘ Define tasks that extend Callable ✘ Submit the parallel tasks 31 Runnable vs Callable vs Future import java.util.concurrent.Future val v1: Future[Int] = service.submit(increment(1)) val v2: Future[Int] = service.submit(increment(2)) How could we use the value of every Future?
  • 32. Callable ✘ Define tasks that extend Callable ✘ Submit the parallel tasks 32 Runnable vs Callable vs Future import java.util.concurrent.Future val v1: Future[Int] = service.submit(increment(1)) val v2: Future[Int] = service.submit(increment(2)) How could we use the value of every Future? trait Future[A] { def get: A }
  • 33. Callable ✘ Define tasks that extend Callable ✘ Submit the parallel tasks 33 Runnable vs Callable vs Future import java.util.concurrent.Future val v1: Future[Int] = service.submit(increment(1)) val v2: Future[Int] = service.submit(increment(2)) STATEMENTS
  • 34. ✘ Define futures Future 34 Runnable vs Callable vs Future def increment(i: Int) = Future.successful(i + 1) val f1: Future[Int] = increment(1) val f2: Future[Int] = increment(2) val result: Future[Int] = for { v1 <- f1 v2 <- f2 } yield v1 + v2
  • 35. ✘ Define futures Future 35 Runnable vs Callable vs Future def increment(i: Int) = Future.successful(i + 1) val f1: Future[Int] = increment(1) val f2: Future[Int] = increment(2) val result: Future[Int] = for { v1 <- f1 v2 <- f2 } yield v1 + v2 Cannot find an implicit ExecutionContext. You might pass [error] an (implicit ec: ExecutionContext) parameter to your method [error] or import scala.concurrent.ExecutionContext.Implicits.global. [error] v2 <- f2 [error] ^
  • 36. ✘ Define futures Future 36 Runnable vs Callable vs Future import scala.concurrent.ExecutionContext.Implicits.global def increment(i: Int) = Future.successful(i + 1) val f1: Future[Int] = increment(1) val f2: Future[Int] = increment(2) val result: Future[Int] = for { v1 <- f1 v2 <- f2 } yield v1 + v2
  • 38. 38 Future Pure Future ✘ Asynchronous ✘ Resumes when the value is ready!
  • 39. 39 Future Pure Future ✘ Asynchronous ✘ Resumes when the value is ready! trait Future[A] { def apply(cb: A => Unit): Unit }
  • 40. 40 Future Pure Future ✘ Asynchronous ✘ Resumes when the value is ready! trait Future[A] { private[api] def apply(cb: A => Unit): Unit }
  • 41. 41 The Data Type for parallel computations Pure Future ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable
  • 42. 42 The Data Type for parallel computations Pure Future type Par[A] = ExecutorService => Future[A] ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable
  • 43. 43 The Data Type for parallel computations Pure Future type Par[A] = ExecutorService => Future[A] ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable
  • 44. 44 The Data Type for parallel computations Pure Future type Par[A] = ExecutorService => Future[A] ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable
  • 45. 45 The Data Type for parallel computations Pure Future object Par { def unit[A](a: A): Par[A] = ??? } ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable
  • 46. 46 Par.unit Pure Future type Par[A] = ExecutorService => Future[A] object Par { def unit[A](a: A): Par[A] = (_: ExecutorService) => new Future[A] { def apply(cb: A => Unit): Unit = cb(a) } }
  • 47. 47 The Data Type for parallel computations Pure Future object Par { def fork[A](a: Par[A]): Par[A] = ??? } ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable
  • 48. 48 Par.fork Pure Future type Par[A] = ExecutorService => Future[A] object Par { def fork[A](a: Par[A]): Par[A] = es => new Future[A] { def apply(cb: A => Unit): Unit = es.submit(new Callable[Unit] { def call: Unit = a(es)(cb) // a(es).apply(cb) }) } }
  • 49. 49 The Data Type for parallel computations Pure Future object Par { def run[A](es: ExecutorService)(par: Par[A]): A = ??? } ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable
  • 50. 50 Par.run Pure Future type Par[A] = ExecutorService => Future[A] object Par { def run[A](es: ExecutorService)(p: Par[A]): A = { val ref = new AtomicReference[A] val latch = new CountDownLatch(1) p(es) { a => ref.set(a) latch.countDown() } latch.await() ref.get } }
  • 51. 51 Par.run Pure Future type Par[A] = ExecutorService => Future[A] object Par { def run[A](es: ExecutorService)(p: Par[A]): A = { val ref = new AtomicReference[A] val latch = new CountDownLatch(1) p(es) { a => ref.set(a) latch.countDown() } latch.await() ref.get } } val one = Par.unit(1) run(es)(one) ⇒ 1
  • 52. “Programming with mutability is like working with the mother-in-law who’s waiting you to fail” - Venkat Subramaniam 52
  • 53. object Par { def map[A, B](a: Par[A])(f: A => B): Par[B] def flatMap[A, B](a: Par[A])(f: A => Par[B]): Par[B] def parMap[A, B](l: List[A])(f: A => B): Par[List[B]] def map2[A, B, C](a: Par[A], b: Par[B])(f: (A, B) => C): Par[C] ... } 53 The Data Type for parallel computations Pure Future ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable
  • 54. 54 The Data Type for parallel computations Pure Future ✘ Requires ExecutorService ✘ Asynchronously performs a given computation of any type ✘ Contains a result of the computation ✘ Composable object Par { def map[A, B](a: Par[A])(f: A => B): Par[B] def flatMap[A, B](a: Par[A])(f: A => Par[B]): Par[B] def parMap[A, B](l: List[A])(f: A => B): Par[List[B]] def map2[A, B, C](a: Par[A], b: Par[B])(f: (A, B) => C): Par[C] ... }
  • 55. Example Pure Future 1 2 3 4 5 6 7 8 9
  • 56. 56 Example Pure Future 1 2 3 4 5 6 7 8 9 def sum(ints: IndexedSeq[Int]): Par[Int] = if (ints.size <= 1) Par.unit(ints.headOption getOrElse 0) else { val (l, r) = ints.splitAt(ints.size / 2) Par.fork(Par.map2(sum(l), sum(r))(_ + _)) }
  • 57. FP Scala libraries ZIO: zio.dev Cats-effect: typelevel.org/cats-effect Monix: monix.io 57 Pure Future
  • 58. References ✘ Functional programming in Scala Book ✘ https://medium.com/@wiemzin/purely-functional-parallelism-in-scala-37ecb1e9999 ✘ https://github.com/fpinscala/fpinscala/blob/master/answers/src/main/scala/fpinscala/paralle lism/Nonblocking.scala 58
  • 59. THANKS! You can find me at @WiemZin @wi101 59