SlideShare a Scribd company logo
1 of 30
Download to read offline
Blocking & Hyper Context
Switching Pattern
ScalaMatsuri 2017
ブロッキング&ハイパーコンテキストスイッチパターン
Agenda
● Introduction
● How did it happen?
● Importance
● Conclusions
アジェンダ
About Me
● Takako Shimamoto (@chibochibo03)
● BizReach, Inc. CTO office
● Scala Warrior: Planning / Illustration
自己紹介
Introduction
はじめに
Notes
● In this session, I don't mention the following:
○ Specifications
○ Selection of libraries
● Instead, we'll use a snippet that demonstrates a
failure pattern
仕様や使用ライブラリの議論はしません
コードは再現したものです
What is it?
def delete(id: Long): Future[Unit] = {
val action = for {
_ <- repository.deleteCategory(id)
...
} yield ()
Try { Await.result(db.run(action.transactionally), Duration.Inf) } match {
case Success(_) => repository.writeLog()
case Failure(e) => Future.failed(e)
}
}
quite a lot generators
returns DBIO[Unit]
returns Future[Unit]
本日のお題
What is it?
● This method is called multiple times per request
● Inject the default Play execution context
このメソッドは1リクエストで複数回呼ばれる
Oh boy!
● The number of users was small
● But response speed worsened gradually
利用者が少ないにも関わらず徐々にレスポンス速度が悪化
Dangers
● Resources were not under stress
○ database connections
○ slow queries
○ access log
● Infrastructure monitoring showed well
外からの監視で異常を検知できない
How did it happen?
何が起きたのか?
The one problem is ...
def delete(id: Long): Future[Unit] = {
val action = for {
_ <- repository.deleteCategory(id)
...
} yield ()
Try { Await.result(db.run(action.transactionally), Duration.Inf) } match {
case Success(_) => repository.writeLog()
case Failure(e) => Future.failed(e)
}
}
quite a lot generators
1つ目の問題は無駄なスイッチング
The precise meaning
The precise meaning of generators and guards is
defined by translation to invocations of four methods:
map, withFilter, flatMap, and foreach.
"6.19 For Comprehensions and For Loops". Scala Language Specification.
https://www.scala-lang.org/files/archive/spec/2.12/, (参照 2017-01-03)
for式は4つのメソッド呼び出しに変換
Implicit ExecutionContexts
● Provide an execution context to execute the given
functions
○ When calling map or flatMap on an action
● In short, an ExecutionContext is a ThreadPool
mapやflatMapは引数に暗黙のスレッドプールが必要
渡した関数はそこで実行
Using a metaphor
C
A
S
H
I
E
R
ファーストフード店で例える
1品ずつ注文
One Hamburger.
A small Coffee.
One French Fry.
Shop
attendant
What the hell !?
C
A
S
H
I
E
R
いやいや、まとめて頼めば1回ですむじゃん!
Shop
attendant
Gather orders!!
Sequential Execution
● DBIO.seq
● DBIO.sequence
○ takes a number of DBIOActions
まとめて渡せるメソッドを使う
The other is ...
def delete(id: Long): Future[Unit] = {
val action = for {
_ <- repository.deleteCategory(id)
...
} yield ()
Try { Await.result(db.run(action.transactionally), Duration.Inf) }
match {
case Success(_) => repository.writeLog()
case Failure(e) => Future.failed(e)
}
}
もう1つの問題はブロッキング
According to Scaladoc
Await.resultはブロッキング
Although this method is blocking, the internal use
of blocking ensures that the underlying
ExecutionContext to properly detect blocking and
ensure that there are no deadlocks.
"scala.concurrent.Await". SCALA API DOCS.
http://www.scala-lang.org/api/2.12.1/scala/concurrent/index.html, (参照 2017-01-03)
Cool names
● More ominous names
○ Oni.blocking(..., Oni.forever)
○ Gachi.blocking(..., Gachi.forever)
● Just kidding! Haha!
名前がカッコよすぎ
鬼ブロック!ガチブロック!(冗談です)
Blocking is evil
● Play is not a traditional web framework
● Play’s thread pools are tuned to use fewer threads
○ IO never blocks
Playは少ないスレッドをブロックせず使い回すスタイル
The C10K problem
● The number of threads multiplies too much
● Lack of resources such as memory
● CPU not busy
クライアント1万台問題
Transformations
変換やコールバックを使う
● Future's methods:
○ map, flatMap, and so on
● Callbacks
○ onComplete, foreach, and so on
Importance
重要なこと
JDBC is synchronous
● A typical example of blocking is database access
● An asynchronous framework doesn't like JDBC
JDBCドライバは同期
Slick’s solution
● Wrap blocking code
○ Blocking happens in a different thread
● Slick has its own thread pool
○ All database actions are executed in this pool
Slickは独自でスレッドプールを持つ
データベースアクションはそのプールのスレッドで実行
Play default thread pool
● It is an Akka dispatcher
● This execution context is backed by a ForkJoinPool
○ Keeping CPU busy
○ Fewer threads are always awake is desirable
AkkaはForkJoinPoolを採用
Blocking in a ForkJoinPool
ForkJoinPoolでブロッキングするとどうなる?
Await.resultをおさらい
● Let's review
Although this method is blocking, the internal use of
blocking ensures that the underlying ExecutionContext to
properly detect blocking and ensure that there are no
deadlocks. "scala.concurrent.Await". SCALA API DOCS.
http://www.scala-lang.org/api/2.12.1/scala/concurrent/index.html, (参照 2017-01-03)
Blocking in a ForkJoinPool
● Inform one is about to block
● It compensates by starting an additional thread
○ Keep available threads for non-blocking operations
○ No upper limit for threads number!!
1つをブロックする代わりに追加のスレッドを生成
上限なし!!
Conclusions
まとめ
Summary
● Await.result + Duration.Inf
● Quite a lot generators
Await.result + Duration.Inf = おやすみ
たくさんのジェネレータ = 東奔西走
Goodnight
zzz
Busy oneself

More Related Content

What's hot

スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyスローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
Yusuke Yamamoto
 

What's hot (19)

JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
ORM Injection
ORM InjectionORM Injection
ORM Injection
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
 
Building Fast, Modern Web Applications with Node.js and CoffeeScript
Building Fast, Modern Web Applications with Node.js and CoffeeScriptBuilding Fast, Modern Web Applications with Node.js and CoffeeScript
Building Fast, Modern Web Applications with Node.js and CoffeeScript
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScript
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Querydsl overview 2014
Querydsl overview 2014Querydsl overview 2014
Querydsl overview 2014
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyスローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby
 
Javascript
JavascriptJavascript
Javascript
 

Viewers also liked

Scala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.jsScala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.js
takezoe
 
Tracing Microservices with Zipkin
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkin
takezoe
 

Viewers also liked (20)

Scala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.jsScala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.js
 
Scala Matsuri 2017
Scala Matsuri 2017Scala Matsuri 2017
Scala Matsuri 2017
 
Preparing for distributed system failures using akka #ScalaMatsuri
Preparing for distributed system failures using akka #ScalaMatsuriPreparing for distributed system failures using akka #ScalaMatsuri
Preparing for distributed system failures using akka #ScalaMatsuri
 
Make your programs Free
Make your programs FreeMake your programs Free
Make your programs Free
 
Reducing Boilerplate and Combining Effects: A Monad Transformer Example
Reducing Boilerplate and Combining Effects: A Monad Transformer ExampleReducing Boilerplate and Combining Effects: A Monad Transformer Example
Reducing Boilerplate and Combining Effects: A Monad Transformer Example
 
Akka-chan's Survival Guide for the Streaming World
Akka-chan's Survival Guide for the Streaming WorldAkka-chan's Survival Guide for the Streaming World
Akka-chan's Survival Guide for the Streaming World
 
7 key recipes for data engineering
7 key recipes for data engineering7 key recipes for data engineering
7 key recipes for data engineering
 
Going bananas with recursion schemes for fixed point data types
Going bananas with recursion schemes for fixed point data typesGoing bananas with recursion schemes for fixed point data types
Going bananas with recursion schemes for fixed point data types
 
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~
 
Akka Cluster and Auto-scaling
Akka Cluster and Auto-scalingAkka Cluster and Auto-scaling
Akka Cluster and Auto-scaling
 
Van laarhoven lens
Van laarhoven lensVan laarhoven lens
Van laarhoven lens
 
Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
 
Dynamic SQL in doobie
Dynamic SQL in doobieDynamic SQL in doobie
Dynamic SQL in doobie
 
Pratical eff
Pratical effPratical eff
Pratical eff
 
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaMatsuri ver)
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaMatsuri ver)The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaMatsuri ver)
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaMatsuri ver)
 
Tracing Microservices with Zipkin
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkin
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
Building A Modern Data Analytics Architecture on AWS
Building A Modern Data Analytics Architecture on AWSBuilding A Modern Data Analytics Architecture on AWS
Building A Modern Data Analytics Architecture on AWS
 
Empowering developers to deploy their own data stores
Empowering developers to deploy their own data storesEmpowering developers to deploy their own data stores
Empowering developers to deploy their own data stores
 
Ways of Seeing Data: Towards a Critical Literacy for Data Visualisations as R...
Ways of Seeing Data: Towards a Critical Literacy for Data Visualisations as R...Ways of Seeing Data: Towards a Critical Literacy for Data Visualisations as R...
Ways of Seeing Data: Towards a Critical Literacy for Data Visualisations as R...
 

Similar to Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern

Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
drewz lin
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
Agora Group
 

Similar to Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern (20)

Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Spock pres
Spock presSpock pres
Spock pres
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Render Caching for Drupal 8
Render Caching for Drupal 8Render Caching for Drupal 8
Render Caching for Drupal 8
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Lobos Introduction
Lobos IntroductionLobos Introduction
Lobos Introduction
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
 
Hibernate
HibernateHibernate
Hibernate
 

More from chibochibo

Spark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with ElasticsearchSpark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with Elasticsearch
chibochibo
 

More from chibochibo (13)

Tour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 MinutesTour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 Minutes
 
Crawler Commons
Crawler CommonsCrawler Commons
Crawler Commons
 
LocalStack
LocalStackLocalStack
LocalStack
 
Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?
 
What is doobie? - database access for scala -
What is doobie? - database access for scala -What is doobie? - database access for scala -
What is doobie? - database access for scala -
 
Quartzでcronを範囲検索したい
Quartzでcronを範囲検索したいQuartzでcronを範囲検索したい
Quartzでcronを範囲検索したい
 
ビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streamingビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streaming
 
nioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になったnioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になった
 
Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-
 
Spark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with ElasticsearchSpark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with Elasticsearch
 
What's a macro?: Learning by Examples
What's a macro?: Learning by ExamplesWhat's a macro?: Learning by Examples
What's a macro?: Learning by Examples
 
Spring Boot Introduction
Spring Boot IntroductionSpring Boot Introduction
Spring Boot Introduction
 
Slick入門
Slick入門Slick入門
Slick入門
 

Recently uploaded

Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
Kayode Fayemi
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
Kayode Fayemi
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
raffaeleoman
 
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
amilabibi1
 

Recently uploaded (18)

Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 
My Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle BaileyMy Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle Bailey
 
ICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdfICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdf
 
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfThe workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
 
Dreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIIDreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio III
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
 
Dreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video TreatmentDreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video Treatment
 
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
 
Causes of poverty in France presentation.pptx
Causes of poverty in France presentation.pptxCauses of poverty in France presentation.pptx
Causes of poverty in France presentation.pptx
 
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
 
Digital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of DrupalDigital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of Drupal
 
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
 
lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.
 
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdfAWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
 
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verifiedSector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
 

Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern

  • 1. Blocking & Hyper Context Switching Pattern ScalaMatsuri 2017 ブロッキング&ハイパーコンテキストスイッチパターン
  • 2. Agenda ● Introduction ● How did it happen? ● Importance ● Conclusions アジェンダ
  • 3. About Me ● Takako Shimamoto (@chibochibo03) ● BizReach, Inc. CTO office ● Scala Warrior: Planning / Illustration 自己紹介
  • 5. Notes ● In this session, I don't mention the following: ○ Specifications ○ Selection of libraries ● Instead, we'll use a snippet that demonstrates a failure pattern 仕様や使用ライブラリの議論はしません コードは再現したものです
  • 6. What is it? def delete(id: Long): Future[Unit] = { val action = for { _ <- repository.deleteCategory(id) ... } yield () Try { Await.result(db.run(action.transactionally), Duration.Inf) } match { case Success(_) => repository.writeLog() case Failure(e) => Future.failed(e) } } quite a lot generators returns DBIO[Unit] returns Future[Unit] 本日のお題
  • 7. What is it? ● This method is called multiple times per request ● Inject the default Play execution context このメソッドは1リクエストで複数回呼ばれる
  • 8. Oh boy! ● The number of users was small ● But response speed worsened gradually 利用者が少ないにも関わらず徐々にレスポンス速度が悪化
  • 9. Dangers ● Resources were not under stress ○ database connections ○ slow queries ○ access log ● Infrastructure monitoring showed well 外からの監視で異常を検知できない
  • 10. How did it happen? 何が起きたのか?
  • 11. The one problem is ... def delete(id: Long): Future[Unit] = { val action = for { _ <- repository.deleteCategory(id) ... } yield () Try { Await.result(db.run(action.transactionally), Duration.Inf) } match { case Success(_) => repository.writeLog() case Failure(e) => Future.failed(e) } } quite a lot generators 1つ目の問題は無駄なスイッチング
  • 12. The precise meaning The precise meaning of generators and guards is defined by translation to invocations of four methods: map, withFilter, flatMap, and foreach. "6.19 For Comprehensions and For Loops". Scala Language Specification. https://www.scala-lang.org/files/archive/spec/2.12/, (参照 2017-01-03) for式は4つのメソッド呼び出しに変換
  • 13. Implicit ExecutionContexts ● Provide an execution context to execute the given functions ○ When calling map or flatMap on an action ● In short, an ExecutionContext is a ThreadPool mapやflatMapは引数に暗黙のスレッドプールが必要 渡した関数はそこで実行
  • 14. Using a metaphor C A S H I E R ファーストフード店で例える 1品ずつ注文 One Hamburger. A small Coffee. One French Fry. Shop attendant
  • 15. What the hell !? C A S H I E R いやいや、まとめて頼めば1回ですむじゃん! Shop attendant Gather orders!!
  • 16. Sequential Execution ● DBIO.seq ● DBIO.sequence ○ takes a number of DBIOActions まとめて渡せるメソッドを使う
  • 17. The other is ... def delete(id: Long): Future[Unit] = { val action = for { _ <- repository.deleteCategory(id) ... } yield () Try { Await.result(db.run(action.transactionally), Duration.Inf) } match { case Success(_) => repository.writeLog() case Failure(e) => Future.failed(e) } } もう1つの問題はブロッキング
  • 18. According to Scaladoc Await.resultはブロッキング Although this method is blocking, the internal use of blocking ensures that the underlying ExecutionContext to properly detect blocking and ensure that there are no deadlocks. "scala.concurrent.Await". SCALA API DOCS. http://www.scala-lang.org/api/2.12.1/scala/concurrent/index.html, (参照 2017-01-03)
  • 19. Cool names ● More ominous names ○ Oni.blocking(..., Oni.forever) ○ Gachi.blocking(..., Gachi.forever) ● Just kidding! Haha! 名前がカッコよすぎ 鬼ブロック!ガチブロック!(冗談です)
  • 20. Blocking is evil ● Play is not a traditional web framework ● Play’s thread pools are tuned to use fewer threads ○ IO never blocks Playは少ないスレッドをブロックせず使い回すスタイル
  • 21. The C10K problem ● The number of threads multiplies too much ● Lack of resources such as memory ● CPU not busy クライアント1万台問題
  • 22. Transformations 変換やコールバックを使う ● Future's methods: ○ map, flatMap, and so on ● Callbacks ○ onComplete, foreach, and so on
  • 24. JDBC is synchronous ● A typical example of blocking is database access ● An asynchronous framework doesn't like JDBC JDBCドライバは同期
  • 25. Slick’s solution ● Wrap blocking code ○ Blocking happens in a different thread ● Slick has its own thread pool ○ All database actions are executed in this pool Slickは独自でスレッドプールを持つ データベースアクションはそのプールのスレッドで実行
  • 26. Play default thread pool ● It is an Akka dispatcher ● This execution context is backed by a ForkJoinPool ○ Keeping CPU busy ○ Fewer threads are always awake is desirable AkkaはForkJoinPoolを採用
  • 27. Blocking in a ForkJoinPool ForkJoinPoolでブロッキングするとどうなる? Await.resultをおさらい ● Let's review Although this method is blocking, the internal use of blocking ensures that the underlying ExecutionContext to properly detect blocking and ensure that there are no deadlocks. "scala.concurrent.Await". SCALA API DOCS. http://www.scala-lang.org/api/2.12.1/scala/concurrent/index.html, (参照 2017-01-03)
  • 28. Blocking in a ForkJoinPool ● Inform one is about to block ● It compensates by starting an additional thread ○ Keep available threads for non-blocking operations ○ No upper limit for threads number!! 1つをブロックする代わりに追加のスレッドを生成 上限なし!!
  • 30. Summary ● Await.result + Duration.Inf ● Quite a lot generators Await.result + Duration.Inf = おやすみ たくさんのジェネレータ = 東奔西走 Goodnight zzz Busy oneself