SlideShare une entreprise Scribd logo
1  sur  60
"Do not block threads!" 
a blessing in disguise or a curse?
Watch the video with slide 
synchronization on InfoQ.com! 
http://www.infoq.com/presentations 
/block-threads 
InfoQ.com: News & Community Site 
• 750,000 unique visitors/month 
• Published in 4 languages (English, Chinese, Japanese and Brazilian 
Portuguese) 
• Post content from our QCon conferences 
• News 15-20 / week 
• Articles 3-4 / week 
• Presentations (videos) 12-15 / week 
• Interviews 2-3 / week 
• Books 1 / month
Presented at QCon London 
www.qconlondon.com 
Purpose of QCon 
- to empower software development by facilitating the spread of 
knowledge and innovation 
Strategy 
- practitioner-driven conference designed for YOU: influencers of 
change and innovation in your teams 
- speakers and topics driving the evolution and innovation 
- connecting and catalyzing the influencers and innovators 
Highlights 
- attended by more than 12,000 delegates since 2007 
- held in 9 cities worldwide
@sadache 
prismic.io co-founder, Play framework co-creator
Modern Applications 
• Spend a considerable time talking to internet 
• Internet means latency 
• How does your runtime integrate this latency?
A Typical Request 
App 
latency 
Service
We should not waste scarce resources 
while waiting for work to be done on other machines 
• Memory, CPU, … 
• Threads/processes? 
• lightweight (millions on a single machines) 
• heavyweight? …
JVM and co 
• Threads are scarce resources (or are they? ) 
• We should not hold to threads while doing IO (or 
internet call) 
• “Do not block threads!”
Copy that! what CAN I do?
Do not block threads! 
• Then what should I do? 
• Non blocking IO and Callbacks 
• ws.get(url, { result => 
println(result) 
}) 
• What happens if I want to do another call after? 
• Callback hell!
Futures! 
(Tasks, Promises, …) 
• Future[T] represents a result of type T that we are 
eventually going to get (at the completion of the 
Future) 
• Doesn’t block the thread 
• But how can I get the T inside? 
• // blocking the current thread until completion of the future? 
Result.await(future)
Examples of Future 
composition 
val eventuallyTweet: Future[String] = … 
val et: Future[Tweet] = eventuallyTweet.map(t => praseTweet(t)) 
! 
val tweets: Seq[Future[Tweet]] = … 
val ts: Future[Seq[Tweet]] = Future.sequence(tweets)
Future composition
Future composition
Future composition
Some syntax sugar 
// for comprehensions 
for { 
t <- getTweet(id) 
k <- getKloutScore(t.user) 
} yield (t,k)
Futures are elegant 
• all, any, monads, applicatives, functors 
• do all the scheduling and synchronisation behind 
the scenes
Future is not satisfactory
Futures are not completely 
satisfactory 
• Manage execution on completion (who is 
responsible of executing the code?) 
• Additional logic complexity (adding one level of 
indirection) 
• Has a big impact on your program (refactorings) 
• Ceremony, or am I doing the compiler/runtime work? 
• Stacktrace gone!
Who runs this code? 
val eventuallyTweet: Future[String] = … 
val et: Future[Tweet] = eventuallyTweet.map(t => praseTweet(t))
Futures are not completely 
satisfactory 
• Manage execution on completion (who is 
responsible of executing the code?) 
• Additional logic complexity (adding one level of 
indirection) 
• Has a big impact on your program (refactorings) 
• Ceremony, or am I doing the compiler/runtime work? 
• Stacktrace gone!
Scala’s solution to execution 
management (on completion) 
• Execution Context 
• def map[S](f: (T) ⇒ S)(implicit executor: ExecutionContext): Future[S] 
• Just import the appropriate EC 
• Very tough to answer the question (developers tend to 
chose the default EC, can lead to contentions) 
• import scala.concurrent.ExecutionContext.global 
• Contention?
Futures are poor man’s 
lightweight threads 
• You might be stuck with them if you’re stuck with 
heavyweight threads… 
• Scala async! 
• Why not an async for the whole program?
Futures are poor man’s 
lightweight threads 
val future = async { 
! 
val f1 = async { ...; true } 
! 
val f2 = async { ...; 42 } 
! 
if (await(f1)) await(f2) else 0 
! 
}
Futures are poor man’s 
lightweight threads 
• You might be stuck with them if you’re stuck with 
heavyweight threads… 
• Scala async 
• Why not an async for the whole program?
Inversion of control 
(Reactive) 
• Future but for multiple values (streams) 
• Just give us a Function and we call you each time 
there is something to do 
• Mouse.onClick { event => println(event) }
Inversion of control 
(Reactive) 
• What about maintaining state across calls 
• Composability and tools 
• Iteratees, RX, Streams, Pipes, Conduits, … etc
Iteratees 
<a quick introduction>
Iteratees 
• What about maintaining state between calls 
• Composability and tools 
• Iteratees, RX, Streams, Pipes, Conduits, … etc
Iteratees 
trait Step 
case class Cont( f:E => Step) extends Step 
case class Done extends Step
Iteratees 
trait Step[E,R] 
case class Cont[E,R]( f:E => Step[E,R]) extends Step[E,R] 
case class Done(r: R) extends Step[Nothing, R]
Iteratees 
// A simple, manually written, Iteratee 
val step = Cont[Int, Int]( e => Done(e)) 
//feeding 1 
step match { 
case Cont(callback) => callback(1) 
case Done(r) => // shouldn’t happen 
}
Counting characters 
// An Iteratee that counts characters 
def charCounter(count:Int = 0): Step[String, Int] = Cont[String, Int]{ 
case Chunk(e) => charCounter(count + e.length) 
case EOF => Done(count) 
}
Iteratees 
trait Input[E] 
case class Chunk[E](e: E) 
case object EOF extends Input[Nothing] 
! 
trait Step[E,R] 
case class Cont[E,R]( f:E => Step[E,R]) extends Step[E,R] 
case class Done(r: R) extends Step[Nothing, R]
Counting characters
Counting characters 
// An Iteratee that counts characters 
def charCounter(count:Int = 0): Step[String, Int] = Cont[String, Int]{ 
case Chunk(e) => step(count + e.length) 
case EOF => Done(count) 
}
Same principle 
• count, getChunks, println, sum, max, min, etc 
• progressive stream fold (fancy fold) 
• Iteratee is the reactive stream consumer
Enumerators 
• Enumerator[E] is the source, it iteratively checks on the Step 
state and feeds input of E if necessary (Cont state) 
• Enumerators can generate, or retrieve, elements from anything 
• Files, sockets, lists, queues, NIO 
• Helper constructors to build different Enumerators
Enumeratees 
• Adapters 
• Apply to Iteratees and/or Enumerators to adapt their input 
• Create new behaviour 
• map, filter, buffer, drop, group, … etc
Iteratees 
</ a quick introduction>
Iteratees 
Inversion of controls: Enumerators chose when to call the Iteratees 
continuation 
They chose on which Thread to run continuation 
What if an Iteratee (or Enumeratee) decided to do a network call? 
Block the thread waiting for a response?
Counting characters 
// An Iteratee that counts characters 
def sumScores(count:Int = 0): Step[String, Int] = Cont[String, Int]{ 
case Chunk(e) => 
val eventuallyScore: Future[Int] = webcalls.getScore(e) 
step(count + Result.await(eventuallyScore)) // seriously??? 
case EOF => Done(count) 
}
Reactive all the way 
// An Iteratee that counts characters 
def sumScores(count:Int = 0): Step[String, Int] = Cont[String, Int]{ 
case Chunk(e) => 
val eventuallyScore: Future[Int] = webcalls.getScore(e) 
step(count + Result.await(eventuallyScore)) // seriously??? 
case EOF => Done(count) 
}
Iteratees 
trait Step[E,R] 
case class Cont[E,R]( f:E => Step[E,R]) extends Step[E,R] 
case class Done(r: R) extends Step[Nothing, R]
Iteratees 
trait Step[E,R] 
case class Cont[E,R]( f:E => Future[Step[E,R]]) extends Step[E,R] 
case class Done(r: R) extends Step[Nothing, R]
Reactive all the way 
// An Iteratee that counts characters 
def sumScores(count:Int = 0): Step[String, Int] = Cont[String, Int]{ 
case Chunk(e) => 
val eventuallyScore: Future[Int] = webcalls.getScore(e) 
eventuallyScore.map( s => step(count + s)) 
case EOF => Future.successful(Done(count)) 
}
Seamless integration between 
Futures and Iteratees 
Seq[Future[E]] is an Enumerator[E] 
Iteratees can integrate any Future returning call 
Back-pressure for free
Suffer from the same 
drawbacks of Futures 
• Manage execution on completion (who is 
responsible of executing the code?) 
• Everything becomes a Future 
• Stacktrace gone!
Elegant, help manage complexity of 
asynchronous multiple messages 
Composable 
Builders and helpers 
Modular
Recap 
• Stuck with heavyweight threads? 
• NIO and Callback hell 
• Futures 
• Composable Futures 
• Iteratees and co 
• Developer suffering from what the runtime/compiler couldn’t 
provide
Asynchronous 
Programming 
is the price you pay, know what you’re paying for
The price is your 
productivity
Asynchronous 
Programming 
calculate your cost effectiveness
Questions
Watch the video with slide synchronization on 
InfoQ.com! 
http://www.infoq.com/presentations/block-threads

Contenu connexe

Plus de C4Media

Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020C4Media
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsC4Media
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No KeeperC4Media
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like OwnersC4Media
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaC4Media
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideC4Media
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDC4Media
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine LearningC4Media
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at SpeedC4Media
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsC4Media
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsC4Media
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerC4Media
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleC4Media
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeC4Media
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereC4Media
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing ForC4Media
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data EngineeringC4Media
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
 
Navigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsNavigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsC4Media
 
High Performance Cooperative Distributed Systems in Adtech
High Performance Cooperative Distributed Systems in AdtechHigh Performance Cooperative Distributed Systems in Adtech
High Performance Cooperative Distributed Systems in AdtechC4Media
 

Plus de C4Media (20)

Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java Applications
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No Keeper
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like Owners
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CD
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep Systems
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.js
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix Scale
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home Everywhere
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing For
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 
Navigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery TeamsNavigating Complexity: High-performance Delivery and Discovery Teams
Navigating Complexity: High-performance Delivery and Discovery Teams
 
High Performance Cooperative Distributed Systems in Adtech
High Performance Cooperative Distributed Systems in AdtechHigh Performance Cooperative Distributed Systems in Adtech
High Performance Cooperative Distributed Systems in Adtech
 

Dernier

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Dernier (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Do Not Block Threads! A Blessing in Disguise or a Curse?

  • 1. "Do not block threads!" a blessing in disguise or a curse?
  • 2. Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations /block-threads InfoQ.com: News & Community Site • 750,000 unique visitors/month • Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese) • Post content from our QCon conferences • News 15-20 / week • Articles 3-4 / week • Presentations (videos) 12-15 / week • Interviews 2-3 / week • Books 1 / month
  • 3. Presented at QCon London www.qconlondon.com Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide
  • 4. @sadache prismic.io co-founder, Play framework co-creator
  • 5. Modern Applications • Spend a considerable time talking to internet • Internet means latency • How does your runtime integrate this latency?
  • 6.
  • 7. A Typical Request App latency Service
  • 8. We should not waste scarce resources while waiting for work to be done on other machines • Memory, CPU, … • Threads/processes? • lightweight (millions on a single machines) • heavyweight? …
  • 9.
  • 10.
  • 11. JVM and co • Threads are scarce resources (or are they? ) • We should not hold to threads while doing IO (or internet call) • “Do not block threads!”
  • 12.
  • 13. Copy that! what CAN I do?
  • 14. Do not block threads! • Then what should I do? • Non blocking IO and Callbacks • ws.get(url, { result => println(result) }) • What happens if I want to do another call after? • Callback hell!
  • 15.
  • 16. Futures! (Tasks, Promises, …) • Future[T] represents a result of type T that we are eventually going to get (at the completion of the Future) • Doesn’t block the thread • But how can I get the T inside? • // blocking the current thread until completion of the future? Result.await(future)
  • 17. Examples of Future composition val eventuallyTweet: Future[String] = … val et: Future[Tweet] = eventuallyTweet.map(t => praseTweet(t)) ! val tweets: Seq[Future[Tweet]] = … val ts: Future[Seq[Tweet]] = Future.sequence(tweets)
  • 21. Some syntax sugar // for comprehensions for { t <- getTweet(id) k <- getKloutScore(t.user) } yield (t,k)
  • 22. Futures are elegant • all, any, monads, applicatives, functors • do all the scheduling and synchronisation behind the scenes
  • 23. Future is not satisfactory
  • 24. Futures are not completely satisfactory • Manage execution on completion (who is responsible of executing the code?) • Additional logic complexity (adding one level of indirection) • Has a big impact on your program (refactorings) • Ceremony, or am I doing the compiler/runtime work? • Stacktrace gone!
  • 25. Who runs this code? val eventuallyTweet: Future[String] = … val et: Future[Tweet] = eventuallyTweet.map(t => praseTweet(t))
  • 26. Futures are not completely satisfactory • Manage execution on completion (who is responsible of executing the code?) • Additional logic complexity (adding one level of indirection) • Has a big impact on your program (refactorings) • Ceremony, or am I doing the compiler/runtime work? • Stacktrace gone!
  • 27. Scala’s solution to execution management (on completion) • Execution Context • def map[S](f: (T) ⇒ S)(implicit executor: ExecutionContext): Future[S] • Just import the appropriate EC • Very tough to answer the question (developers tend to chose the default EC, can lead to contentions) • import scala.concurrent.ExecutionContext.global • Contention?
  • 28. Futures are poor man’s lightweight threads • You might be stuck with them if you’re stuck with heavyweight threads… • Scala async! • Why not an async for the whole program?
  • 29. Futures are poor man’s lightweight threads val future = async { ! val f1 = async { ...; true } ! val f2 = async { ...; 42 } ! if (await(f1)) await(f2) else 0 ! }
  • 30. Futures are poor man’s lightweight threads • You might be stuck with them if you’re stuck with heavyweight threads… • Scala async • Why not an async for the whole program?
  • 31. Inversion of control (Reactive) • Future but for multiple values (streams) • Just give us a Function and we call you each time there is something to do • Mouse.onClick { event => println(event) }
  • 32. Inversion of control (Reactive) • What about maintaining state across calls • Composability and tools • Iteratees, RX, Streams, Pipes, Conduits, … etc
  • 33. Iteratees <a quick introduction>
  • 34. Iteratees • What about maintaining state between calls • Composability and tools • Iteratees, RX, Streams, Pipes, Conduits, … etc
  • 35. Iteratees trait Step case class Cont( f:E => Step) extends Step case class Done extends Step
  • 36. Iteratees trait Step[E,R] case class Cont[E,R]( f:E => Step[E,R]) extends Step[E,R] case class Done(r: R) extends Step[Nothing, R]
  • 37. Iteratees // A simple, manually written, Iteratee val step = Cont[Int, Int]( e => Done(e)) //feeding 1 step match { case Cont(callback) => callback(1) case Done(r) => // shouldn’t happen }
  • 38. Counting characters // An Iteratee that counts characters def charCounter(count:Int = 0): Step[String, Int] = Cont[String, Int]{ case Chunk(e) => charCounter(count + e.length) case EOF => Done(count) }
  • 39. Iteratees trait Input[E] case class Chunk[E](e: E) case object EOF extends Input[Nothing] ! trait Step[E,R] case class Cont[E,R]( f:E => Step[E,R]) extends Step[E,R] case class Done(r: R) extends Step[Nothing, R]
  • 41. Counting characters // An Iteratee that counts characters def charCounter(count:Int = 0): Step[String, Int] = Cont[String, Int]{ case Chunk(e) => step(count + e.length) case EOF => Done(count) }
  • 42. Same principle • count, getChunks, println, sum, max, min, etc • progressive stream fold (fancy fold) • Iteratee is the reactive stream consumer
  • 43. Enumerators • Enumerator[E] is the source, it iteratively checks on the Step state and feeds input of E if necessary (Cont state) • Enumerators can generate, or retrieve, elements from anything • Files, sockets, lists, queues, NIO • Helper constructors to build different Enumerators
  • 44. Enumeratees • Adapters • Apply to Iteratees and/or Enumerators to adapt their input • Create new behaviour • map, filter, buffer, drop, group, … etc
  • 45. Iteratees </ a quick introduction>
  • 46. Iteratees Inversion of controls: Enumerators chose when to call the Iteratees continuation They chose on which Thread to run continuation What if an Iteratee (or Enumeratee) decided to do a network call? Block the thread waiting for a response?
  • 47. Counting characters // An Iteratee that counts characters def sumScores(count:Int = 0): Step[String, Int] = Cont[String, Int]{ case Chunk(e) => val eventuallyScore: Future[Int] = webcalls.getScore(e) step(count + Result.await(eventuallyScore)) // seriously??? case EOF => Done(count) }
  • 48. Reactive all the way // An Iteratee that counts characters def sumScores(count:Int = 0): Step[String, Int] = Cont[String, Int]{ case Chunk(e) => val eventuallyScore: Future[Int] = webcalls.getScore(e) step(count + Result.await(eventuallyScore)) // seriously??? case EOF => Done(count) }
  • 49. Iteratees trait Step[E,R] case class Cont[E,R]( f:E => Step[E,R]) extends Step[E,R] case class Done(r: R) extends Step[Nothing, R]
  • 50. Iteratees trait Step[E,R] case class Cont[E,R]( f:E => Future[Step[E,R]]) extends Step[E,R] case class Done(r: R) extends Step[Nothing, R]
  • 51. Reactive all the way // An Iteratee that counts characters def sumScores(count:Int = 0): Step[String, Int] = Cont[String, Int]{ case Chunk(e) => val eventuallyScore: Future[Int] = webcalls.getScore(e) eventuallyScore.map( s => step(count + s)) case EOF => Future.successful(Done(count)) }
  • 52. Seamless integration between Futures and Iteratees Seq[Future[E]] is an Enumerator[E] Iteratees can integrate any Future returning call Back-pressure for free
  • 53. Suffer from the same drawbacks of Futures • Manage execution on completion (who is responsible of executing the code?) • Everything becomes a Future • Stacktrace gone!
  • 54. Elegant, help manage complexity of asynchronous multiple messages Composable Builders and helpers Modular
  • 55. Recap • Stuck with heavyweight threads? • NIO and Callback hell • Futures • Composable Futures • Iteratees and co • Developer suffering from what the runtime/compiler couldn’t provide
  • 56. Asynchronous Programming is the price you pay, know what you’re paying for
  • 57. The price is your productivity
  • 58. Asynchronous Programming calculate your cost effectiveness
  • 60. Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations/block-threads