SlideShare a Scribd company logo
1 of 72
Flying Futuresat thesameskycan
makethesunriseatmidnight!
Wiem Zine Elabidine
...The Journey...
Parallelism &Concurrency
Threads andFutures
Concurrency problems
Solutions
Parallelism&Concurrency01
Parallelism
“Parallel computing is a form of
computation in which many calculations
are carried out simultaneously” - Wikipedia
Concurrency
“Concurrency refers to the ability of different
parts or units of a program, algorithm, or
problem to be executed out-of-order or in
partial order, without affecting the final
outcome.” - Wikipedia
4Cores
Parallelism Concurrency
4Cores
Parallelism Concurrency
1Core
Parallelism Concurrency
ThreadsandFutures02Describe parallel computations
Thread
A linear flow of execution
managed by a Scheduler.
def task(i: Int) =
new Thread{() =>
println(s"Instruction 1: Task $i")
println(s"Instruction 2: Task $i")
}
task(1).start()
task(2).start()
Thread
A linear flow of execution
managed by a Scheduler.
> run
instruction 1: Task 1
instruction 1: Task 2
instruction 2: Task 1
instruction 2: Task 2
Thread
A linear flow of execution
managed by a Scheduler.
> run
instruction 1: Task 1
instruction 1: Task 2
instruction 2: Task 2
instruction 2: Task 1
Thread
A linear flow of execution
managed by a Scheduler.
> run
instruction 1: Task 2
instruction 2: Task 2
instruction 1: Task 1
instruction 2: Task 1
Depends to the number of the
instructions and the number of
threads.
Executionorder
Possibleexec Paths
Depends to the number of the
instructions and the number of
threads.
Executionorder
PossibleexecutionPaths
- 2 Instructions
- 2 Threads
- 24/4 = 6
⇒ 6 Possible results
def task(i: Int) =
new Thread{() =>
println(s"Instruction 1: Task $i")
println(s"Instruction 2: Task $i")
}
task(1).start()
task(2).start()
1Thread=1OSThread
1Thread=1OSThread
Runtime.getRuntime.availableProcessors
ThreadPool
Task1 Task2 Task3 Task4 ...Tasks Queue
Thread Pool
ThreadPoolExecutor
. Helps to save resources
. Control the number of
the created threads in
the application.
def task(i: Int) =
new Thread{() =>
println(s"Iteration 1: Task $i")
println(s"Iteration 2: Task $i")
}
val service: ExecutorService =
Executors.newFixedThreadPool(2)
(1 to 1000).foreach(i =>
service.submit(task(i)))
def task(i: Int) =
new Thread{() =>
println(s"Iteration 1: Task $i")
println(s"Iteration 2: Task $i")
}
val service: ExecutorService =
Executors.newFixedThreadPool(2)
(1 to 1000).foreach(i =>
service.submit(task(i)))
ThreadPoolExecutor
. Helps to save resources
. Control the number of
the created threads in
the application.
def task(i: Int): Future[Unit] =
Future{
println(s"Iteration 1: Task $i")
println(s"Iteration 2: Task $i")
}
(1 to 1000).foreach(task)
ScalaFuture
Describe a non blocking
computation.
def task(i: Int): Future[Unit] =
Future{
println(s"Iteration 1: Task $i")
println(s"Iteration 2: Task $i")
}
(1 to 1000).foreach(task)
ScalaFuture
Describe a non blocking
computation.
The performance of the program depends to your CPU
The performance of the program depends to your CPU
implicit val es =
ExecutionContext.fromExecutor(
Executors.newFixedThreadPool(2))
Futures
Composabledef deleteProfile(userId: UserId) =
for {
d1 <- deleteUser(userId)
d2 <- deletePicture(userId)
d3 <- deleteEducation(userId)
} yield d1 && d2 && d3
def deleteProfile(userId: UserId) = {
val f1 = users.deleteUser(userId)
val f2 = users.deletePicture(userId)
val f3 = users.deleteEducation(userId)
users.exists(userId).flatMap {
check => if(check)
for {
_ <- f1
_ <- f2
_ <- f3
} yield ()
}
}
FlyingFutures
def deleteProfile(userId: UserId) = {
users.exists(userId).flatMap {
check => if(check)
for {
_ <- users.deleteUser(userId)
_ <- users.deletePicture(userId)
_ <- users.deleteEducation(userId)
} yield ()
}
}
FlyingFutures
Await.result
lazy val flyingFuture =
Future {
Thread.sleep(2000)
println(
"after 2 seconds I am still flying!"
)}
Await.result(flyingFuture, 1.second)
TimeOutException
TimeOutException
TimeOutExceptionwillnotstoptheflyingFuture!
Not referential transparent
Futures aren’treferentialtransparent
def deleteProfile(userId: UserId) =
for {
d1 <- deleteUser(userId)
d2 <- deletePicture(userId)
d3 <- deleteEducation(userId)
} yield d1 && d2 && d3
def deleteProfile(userId: UserId) = {
val f1 = deleteUser(userId)
val f2 = deletePicture(userId)
val f3 = deleteEducation(userId)
for {
d1 <- f1
d2 <- f2
d3 <- f3
} yield d1 && d2 && d3
}
LazyFutures don’tfly
def deleteProfile(userId: UserId) =
for {
d1 <- deleteUser(userId)
d2 <- deletePicture(userId)
d3 <- deleteEducation(userId)
} yield d1 && d2 && d3
def deleteProfile(userId: UserId) = {
lazy val f1 = deleteUser(userId)
lazy val f2 = deletePicture(userId)
lazy val f3 = deleteEducation(userId)
for {
d1 <- f1
d2 <- f2
d3 <- f3
} yield d1 && d2 && d3
}
No Future, No fly
ConcurrencyProblems
case class State(
sunState: Sun.State,
moonState: Moon.State,
earthState: Earth.State
)
val changeSunState: Future[State] =
computeSunState.map { v =>
state = state.copy(sunState = v)
}
val changeMoonState: Future[State] =
computeMoonState.map { v =>
state = state.copy(moonState = v)
}
val changeEarthState: Future[State] =
computeEarthState.map { v =>
state = state.copy(earthState = v)
}
case class State(
sunState: Sun.State,
moonState: Moon.State,
earthState: Earth.State
)
The devil is in mutable state
MemoryArchitecture: 4Cores
Core 1 Core 2 Core 3 Core 4
registers registers registers registers
LC LC LC LC
Main memory
MutableState
Sun Earth Moon
23:58
Core 1 Core 2 Core 3
registers registers registers
LC LC LC
Main memory
state
state state state
MutableState
Sun Earth Moon
23:58
Core 1 Core 2 Core 3
registers registers registers
LC LC LC
Main memory
state
state state state
MutableState
Sun Earth Moon
23:58
Core 1 Core 2 Core 3
registers registers registers
LC LC LC
Main memory
state
state state state
Raceconditions
MutableState
Sun Earth Moon
23:58
00:00
Core 1 Core 2 Core 3
registers registers registers
LC LC LC
Main memory
state
state state state
Flying Futuresinthesameskycan
makethesunriseatmidnight
Solutions
Solutions
- For the visibility problem:
● volatile
Solutions
- For the visibility problem:
● volatile
- For the synchronization problem:
● synchronized
● AtomicReference
● CountDownLatch
● Locks
● Semaphores
Control the interactions with
the outside World
Functionaleffects
DatatypesforParallel
computation
IO[E,A]
Models Sync, Async effects
Fiber[E,A]
Models a running IO value
DatatypesforParallel
computation
IO[E,A]
Models Sync, Async effects
Fiber[E,A]
Models a running IO value
val f: IO[Nothing, Fiber[Nothing, Unit] =
io.fork
val io: IO[Nothing, Unit] =
IO.effectTotal(println("Hello"))
ZIOisreferentialtransparent
def deleteProfile(userId: UserId) =
for {
d1 <- deleteUser(userId)
d2 <- deletePicture(userId)
d3 <- deleteEducation(userId)
} yield ()
def deleteProfile(userId: UserId) = {
val f1 = deleteUser(userId)
val f2 = deletePicture(userId)
val f3 = deleteEducation(userId)
for {
d1 <- f1
d2 <- f2
d3 <- f3
} yield ()
}
ZIOisreferentialtransparent
def deleteProfile(userId: UserId) =
for {
d1 <- deleteUser(userId).fork
d2 <- deletePicture(userId).fork
d3 <- deleteEducation(userId).fork
} yield ()
def deleteProfile(userId: UserId) = {
val f1 = deleteUser(userId).fork
val f2 = deletePicture(userId).fork
val f3 = deleteEducation(userId).fork
for {
d1 <- f1
d2 <- f2
d3 <- f3
} yield ()
}
def deleteProfile(userId: UserId) =
ZIO.collectAllPar(
deleteUser(userId) ::
deletePicture(userId) ::
deleteEducation(userId) ::
Nil)
Paralleltasks
ZIOSTM
Provides the ability to atomically commit a series of reads and
writes to transactional memory when a set of conditions is
satisfied.
STM[E,A]
Describes a transaction Describes the transactional
memory that will be read and
written inside the transaction
TRef[A]
Example
def changeSunState(tState: TRef[State]): STM[Nothing, State] =
computeSunState.map { v =>
state =
tState.update(_.copy(sunState = v))
}
def changeSunState(tState: TRef[State]) =
computeSunState.map { v =>
state =
tState.update(_.copy(sunState = v))
}
def changeMoonState(tState: TRef[State]) =
computeMoonState.map { v =>
state =
tState.update(_.copy(moonState = v))
}
def changeEarthState(tState: TRef[State])=
computeEarthState.map { v =>
state =
tState.update(_.copy(earthState = v))
}
Transaction 1
Transaction 2
Transaction 3
tState
Example
def changeSunState(tState: TRef[State]) =
computeSunState.map { v =>
state =
tState.update(_.copy(sunState = v))
}
def changeMoonState(tState: TRef[State]) =
computeMoonState.map { v =>
state =
tState.update(_.copy(moonState = v))
}
def changeEarthState(tState: TRef[State])=
computeEarthState.map { v =>
state =
tState.update(_.copy(earthState = v))
}
object SolarSystem {
def make(initialState: State) =
for {
tstate <- TRef.make(initialState).commit
_ <- changeSunState(tstate).commit.fork
_ <- changeMoonState(tstate).commit.fork
_ <- changeEarthState(tstate).commit.fork
} yield ()
}
Execution
Sun Earth Moon
def changeSunState(tState: TRef[State]) =
computeSunState.map { v =>
state =
tState.update(_.copy(sunState = v))
}
def changeMoonState(tState: TRef[State]) =
computeMoonState.map { v =>
state =
tState.update(_.copy(moonState = v))
}
def changeEarthState(tState: TRef[State])=
computeEarthState.map { v =>
state =
tState.update(_.copy(earthState = v))
}
Execution
Sun Earth Moon
def changeSunState(tState: TRef[State]) =
computeSunState.map { v =>
state =
tState.update(_.copy(sunState = v))
}
def changeMoonState(tState: TRef[State]) =
computeMoonState.map { v =>
state =
tState.update(_.copy(moonState = v))
}
def changeEarthState(tState: TRef[State])=
computeEarthState.map { v =>
state =
tState.update(_.copy(earthState = v))
}
Execution
Sun Earth Moon
def changeSunState(tState: TRef[State]) =
computeSunState.map { v =>
state =
tState.update(_.copy(sunState = v))
}
def changeMoonState(tState: TRef[State]) =
computeMoonState.map { v =>
state =
tState.update(_.copy(moonState = v))
}
def changeEarthState(tState: TRef[State])=
computeEarthState.map { v =>
state =
tState.update(_.copy(earthState = v))
}
Example
def changeSunState(tState: TRef[State]) =
computeSunState.map { v =>
state =
tState.update(_.copy(sunState = v))
}
def changeMoonState(tState: TRef[State]) =
computeMoonState.map { v =>
state =
tState.update(_.copy(moonState = v))
}
def changeEarthState(tState: TRef[State])=
computeEarthState.map { v =>
state =
tState.update(_.copy(earthState = v))
}
object SolarSystem {
def make(initialState: State) =
for {
tstate <- TRef.makeCommit(initialState)
_ <- changeSunState(tstate).commit.fork
_ <- changeMoonState(tstate).commit.fork
_ <- changeEarthState(tstate).commit.fork
} yield ()
}
Concurrencyistrickybutitmakes
yourapplicationresponsiveand
faster
Useful links
Concurrency is complicated
★ https://medium.com/@wiemzin
★ ZIO-STM: https://github.com/zio/zio
★ Akka Actor
★ Upgrade your Future by John De Goes
★ Functional programminglibraries: ZIO, Cats effects, Monix
★ Presentation template by Slidesgo
Wiem Zine Elabidine
twitter: @WiemZin
github: wi101
THANKS

More Related Content

What's hot

Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIOJohn 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
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsJorge Vásquez
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsJohn De Goes
 
An Introduction to Property Based Testing
An Introduction to Property Based TestingAn Introduction to Property Based Testing
An Introduction to Property Based TestingC4Media
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga beginsDaniel Franz
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testingScott Wlaschin
 
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
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
 
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional ProgrammingZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional ProgrammingJohn De Goes
 
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
 
Property-Based Testing
Property-Based TestingProperty-Based Testing
Property-Based TestingShai Geva
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldJorge Vásquez
 
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
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsScott Wlaschin
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 

What's hot (20)

Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIO
 
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
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effects
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
An Introduction to Property Based Testing
An Introduction to Property Based TestingAn Introduction to Property Based Testing
An Introduction to Property Based Testing
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
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
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional ProgrammingZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
ZIO Schedule: Conquering Flakiness & Recurrence with Pure Functional Programming
 
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
 
Property-Based Testing
Property-Based TestingProperty-Based Testing
Property-Based Testing
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
 
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
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of tests
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Akka tips
Akka tipsAkka tips
Akka tips
 

Similar to Flying Futures at the same sky can make the sun rise at midnight

Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoofelixtrepanier
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Exactly once with spark streaming
Exactly once with spark streamingExactly once with spark streaming
Exactly once with spark streamingQuentin Ambard
 
Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Hyuk Hur
 
How to Develop Your Own Simulators for Discrete-Event Systems
How to Develop Your Own Simulators for Discrete-Event SystemsHow to Develop Your Own Simulators for Discrete-Event Systems
How to Develop Your Own Simulators for Discrete-Event SystemsDonghun Kang
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMsunng87
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and ProfitAdil Akhter
 
Functional programming with clojure
Functional programming with clojureFunctional programming with clojure
Functional programming with clojureLucy Fang
 
Extracting a Micro State Transition Table Using KLEE
Extracting a Micro State Transition Table Using KLEEExtracting a Micro State Transition Table Using KLEE
Extracting a Micro State Transition Table Using KLEENorihiro Yoshida
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)Jacek Laskowski
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
Memento Pattern Implementation
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern ImplementationSteve Widom
 
Constraint Programming in Haskell
Constraint Programming in HaskellConstraint Programming in Haskell
Constraint Programming in HaskellDavid Overton
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35Bilal Ahmed
 

Similar to Flying Futures at the same sky can make the sun rise at midnight (20)

Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Exactly once with spark streaming
Exactly once with spark streamingExactly once with spark streaming
Exactly once with spark streaming
 
Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"
 
How to Develop Your Own Simulators for Discrete-Event Systems
How to Develop Your Own Simulators for Discrete-Event SystemsHow to Develop Your Own Simulators for Discrete-Event Systems
How to Develop Your Own Simulators for Discrete-Event Systems
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and Profit
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Functional programming with clojure
Functional programming with clojureFunctional programming with clojure
Functional programming with clojure
 
Extracting a Micro State Transition Table Using KLEE
Extracting a Micro State Transition Table Using KLEEExtracting a Micro State Transition Table Using KLEE
Extracting a Micro State Transition Table Using KLEE
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Memento Pattern Implementation
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern Implementation
 
Constraint Programming in Haskell
Constraint Programming in HaskellConstraint Programming in Haskell
Constraint Programming in Haskell
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 

Recently uploaded

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 

Recently uploaded (20)

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 

Flying Futures at the same sky can make the sun rise at midnight

Editor's Notes

  1. todo example & slide for zio.fork fiber.join.timeout(1.second)
  2. if you have concurrent program there is soth to deal with and to achieve having a concurrent program is that yopur program return a correcrt result and the concurrent computations shouldn’t affect to your output Concurrent programming is the management of sharing and timing.
  3. a linear flow of execution that can be managed independently by a Scheduler, a Scheduler, is a part of the Operating System that decides which process runs at a certain point in time. The time each thread receives is non-deterministic, which makes concurrency tricky.
  4. a linear flow of execution that can be managed independently by a Scheduler,
  5. a linear flow of execution that can be managed independently by a Scheduler,
  6. a linear flow of execution that can be managed independently by a Scheduler,
  7. Every statement in a program is translated into many CPU instructions
  8. For N instructions and T threads there are N * T steps, there is a context switch between the T threads on each step. From Clean Code Book page 322
  9. 2 Instructions and 2 Threads so we can have (24 /4 = 6) 6 possible results: I1T1I2T2, I1T2I1T2, I1T2I2T1, I2T1I1T2, I2T1I2T1, I2T2I1T1
  10. But what if you want to run 100 tasks Depending to the number of available cores
  11. if you have 4 cores you will have 4 threads running in parallel and the other threads will be suspended And Creating a thread is an expensive operation
  12. What you can do is to define a fixed number of threads: Pool of threads which is represented in a blocked queue The thread pool execution uses a blocking queue. It keeps storing all the tasks that you have submitted to the executor service, and all threads (workers) are always running and performing the same steps: Take the Task from the queue Execute it Take the next or wait until a task will be added to the queue
  13. * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue. * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue. At any point, at most * {@code nThreads} threads will be active processing tasks. * If additional tasks are submitted when all threads are active, * they will wait in the queue until a thread is available. * If any thread terminates due to a failure during execution * prior to shutdown, a new one will take its place if needed to * execute subsequent tasks. The threads in the pool will exist * until it is explicitly {@link ExecutorService#shutdown shutdown}.
  14. The global execution context sets maxThreads depending to the number of the available cores on the system. It means when you run a concurrent Futures using global execution context, the performance of your program depends on the number of the processors available to the JVM.
  15. The global execution context sets maxThreads depending to the number of the available cores on the system. It means when you run a concurrent Futures using global execution context, the performance of your program depends on the number of the processors available to the JVM.
  16. The program changes its meaning in the left hand side it is sequential in the right hand side it is in parallel
  17. The program changes its meaning in the left hand side it is sequential in the right hand side it is in parallel
  18. The program changes its meaning in the left hand side it is sequential in the right hand side it is in parallel
  19. The program changes its meaning in the left hand side it is sequential in the right hand side it is in parallel
  20. The program changes its meaning in the left hand side it is sequential in the right hand side it is in parallel
  21. The program changes its meaning in the left hand side it is sequential in the right hand side it is in parallel
  22. - you can treat your program as data, passing it around to other functions and composing it with other data, and thus reach more structured and composable code.
  23. The program changes its meaning in the left hand side it is sequential in the right hand side it is in parallel
  24. The program changes its meaning in the left hand side it is sequential in the right hand side it is in parallel
  25. - you can treat your program as data, passing it around to other functions and composing it with other data, and thus reach more structured and composable code.
  26. referential transparency: no surprises you can think to make your future lazy or use FP library for effectful computation that describes programs as values which makes the expression referencial transparent make thing immutable, but in case you need that, you would have to use locks/semaphore/ or if you already chose to use a FP librarty ZIO provides a data structure that enables you to define a transaction with transactional references that
  27. the earth determin the day/night using the state of the sun and the moon the moon computes which phase it would be in at any point in time, change its state using the sun state the sun changes its own state and leave the same moon and earth state at midnight the moonn phases supposed to be changed but at that point in time the sun state has been updated by the sun and the recent change of the moon wasn’t been considered, the earth computed its state using the sun and the moon state and the sun rises due to this a race condition
  28. JVM dealing with mutable state is really a problem that we should consider we have to work hard to prevent starvation deadlocks race conditions How threads interact through memory?
  29. registers perform the operations very fast and cache memory layers can be accessed by the CPU All cores can access to the main memory when a CPU needs to access main memory it will read part of main memory into its CPU cache. some CPUS might have multiple cache layers (Level 1 and Level 2), It may even read part of the cache into its internal registers and then perform operations on it. When the CPU needs to write the result back to main memory it will flush the value from its internal register to the cache memory, and at some point flush the value back to main memory. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores it will be sent to the main memory, and this takes time
  30. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  31. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  32. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  33. A race condition is a special condition that may occur inside a critical section. A critical section is a section of code that is executed by multiple threads and where the sequence of execution for the threads makes a difference in the result of the concurrent execution of the critical section
  34. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  35. . Copying the change made by the threads which means the writing thread crosses the memory barrier and the the read thread crossed the memory barrier synchronized and volatile keywords force that the changes are globally visible on a timely basis; these help cross the memory barrier—accidentally or intentionally. But the solutions will reduce the performace of the program
  36. . Copying the change made by the threads which means the writing thread crosses the memory barrier and the the read thread crossed the memory barrier synchronized and volatile keywords force that the changes are globally visible on a timely basis; these help cross the memory barrier—accidentally or intentionally. But the solutions will reduce the performace of the program
  37. For N instructions and T threads there are N * T steps, there is a context switch between the T threads on each step. From Clean Code Book page 322
  38. but this program is sequential
  39. but this program is sequential
  40. to describe a parallel computation you onlyt have to call
  41. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  42. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  43. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  44. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  45. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time
  46. Executing the load/store in memory is done to exchange the information between caches. Stores are more expensive than loads! the results have to be shared between other cores, and this takes time