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

C
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
1 of 30

Recommended

Zen of Akka by
Zen of AkkaZen of Akka
Zen of AkkaKonrad Malawski
29.4K views136 slides
Java 7 Language Enhancement by
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancementmuthusvm
1.3K views20 slides
Scala Refactoring for Fun and Profit (Japanese subtitles) by
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Tomer Gabel
6.6K views16 slides
ORM2Pwn: Exploiting injections in Hibernate ORM by
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMMikhail Egorov
42.3K views28 slides
Ten useful JavaScript tips & best practices by
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
3.5K views52 slides
Questioning the status quo by
Questioning the status quoQuestioning the status quo
Questioning the status quoIvano Pagano
2.2K views83 slides

More Related Content

What's hot

JavaScript - From Birth To Closure by
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
51.9K views133 slides
ORM Injection by
ORM InjectionORM Injection
ORM InjectionSimone Onofri
11.2K views38 slides
#살아있다 #자프링외길12년차 #코프링2개월생존기 by
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
1.8K views82 slides
Ajax Security by
Ajax SecurityAjax Security
Ajax SecurityJoe Walker
42.6K views83 slides
Building Fast, Modern Web Applications with Node.js and CoffeeScript by
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 CoffeeScriptroyaldark
9.5K views37 slides
Clean code in JavaScript by
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScriptMathieu Breton
198 views40 slides

What's hot(19)

JavaScript - From Birth To Closure by Robert Nyman
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
Robert Nyman51.9K views
#살아있다 #자프링외길12년차 #코프링2개월생존기 by Arawn Park
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park1.8K views
Ajax Security by Joe Walker
Ajax SecurityAjax Security
Ajax Security
Joe Walker42.6K views
Building Fast, Modern Web Applications with Node.js and CoffeeScript by royaldark
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
royaldark9.5K views
Everything is Permitted: Extending Built-ins by Andrew Dupont
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
Andrew Dupont8K views
Singletons in PHP - Why they are bad and how you can eliminate them from your... by go_oh
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...
go_oh43.5K views
Powerful JavaScript Tips and Best Practices by Dragos Ionita
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita577 views
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy by Yusuke Yamamoto
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyスローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
Yusuke Yamamoto6.4K views
Практики применения JRuby by .toster
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby
.toster967 views
Javascript by theacadian
JavascriptJavascript
Javascript
theacadian1.4K views

Viewers also liked

Scala Warrior and type-safe front-end development with Scala.js by
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.jstakezoe
9.3K views49 slides
Scala Matsuri 2017 by
Scala Matsuri 2017Scala Matsuri 2017
Scala Matsuri 2017Yoshitaka Fujii
2.1K views66 slides
Preparing for distributed system failures using akka #ScalaMatsuri by
Preparing for distributed system failures using akka #ScalaMatsuriPreparing for distributed system failures using akka #ScalaMatsuri
Preparing for distributed system failures using akka #ScalaMatsuriTIS Inc.
6.4K views68 slides
Make your programs Free by
Make your programs FreeMake your programs Free
Make your programs FreePawel Szulc
3.9K views149 slides
Reducing Boilerplate and Combining Effects: A Monad Transformer Example by
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 ExampleConnie Chen
2.5K views25 slides
Akka-chan's Survival Guide for the Streaming World by
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 WorldKonrad Malawski
5.4K views136 slides

Viewers also liked(20)

Scala Warrior and type-safe front-end development with Scala.js by takezoe
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
takezoe9.3K views
Preparing for distributed system failures using akka #ScalaMatsuri by TIS Inc.
Preparing for distributed system failures using akka #ScalaMatsuriPreparing for distributed system failures using akka #ScalaMatsuri
Preparing for distributed system failures using akka #ScalaMatsuri
TIS Inc.6.4K views
Make your programs Free by Pawel Szulc
Make your programs FreeMake your programs Free
Make your programs Free
Pawel Szulc3.9K views
Reducing Boilerplate and Combining Effects: A Monad Transformer Example by Connie Chen
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
Connie Chen2.5K views
Akka-chan's Survival Guide for the Streaming World by Konrad Malawski
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
Konrad Malawski5.4K views
7 key recipes for data engineering by univalence
7 key recipes for data engineering7 key recipes for data engineering
7 key recipes for data engineering
univalence 3.2K views
Going bananas with recursion schemes for fixed point data types by Pawel Szulc
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
Pawel Szulc2.2K views
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~ by Masahito Zembutsu
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~
Masahito Zembutsu60.9K views
Akka Cluster and Auto-scaling by Ikuo Matsumura
Akka Cluster and Auto-scalingAkka Cluster and Auto-scaling
Akka Cluster and Auto-scaling
Ikuo Matsumura2.9K views
Van laarhoven lens by Naoki Aoyama
Van laarhoven lensVan laarhoven lens
Van laarhoven lens
Naoki Aoyama1.9K views
Reactive integrations with Akka Streams by Konrad Malawski
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
Konrad Malawski1.9K views
Dynamic SQL in doobie by chibochibo
Dynamic SQL in doobieDynamic SQL in doobie
Dynamic SQL in doobie
chibochibo1.6K views
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaMatsuri ver) by Eugene Yokota
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)
Eugene Yokota1.4K views
Tracing Microservices with Zipkin by takezoe
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkin
takezoe13.8K views
What to Upload to SlideShare by SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
SlideShare14.4M views
Building A Modern Data Analytics Architecture on AWS by Amazon Web Services
Building A Modern Data Analytics Architecture on AWSBuilding A Modern Data Analytics Architecture on AWS
Building A Modern Data Analytics Architecture on AWS
Amazon Web Services6.4K views
Empowering developers to deploy their own data stores by Tomas Doran
Empowering developers to deploy their own data storesEmpowering developers to deploy their own data stores
Empowering developers to deploy their own data stores
Tomas Doran23.1K views
Ways of Seeing Data: Towards a Critical Literacy for Data Visualisations as R... by Jonathan Gray
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...
Jonathan Gray23.1K views

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

Java 7 Whats New(), Whats Next() from Oredev by
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
2.2K views84 slides
New Features Of JDK 7 by
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
10.5K views41 slides
Blocks & GCD by
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
2.4K views32 slides
Java 7 & 8 New Features by
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New FeaturesLeandro Coutinho
280 views60 slides
Appsec usa2013 js_libinsecurity_stefanodipaola by
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaoladrewz lin
894 views41 slides
55 New Features in Java 7 by
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7Boulder Java User's Group
70.9K views63 slides

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

Java 7 Whats New(), Whats Next() from Oredev by Mattias Karlsson
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
Mattias Karlsson2.2K views
New Features Of JDK 7 by Deniz Oguz
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
Deniz Oguz10.5K views
Blocks & GCD by rsebbe
Blocks & GCDBlocks & GCD
Blocks & GCD
rsebbe2.4K views
Appsec usa2013 js_libinsecurity_stefanodipaola by drewz lin
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
drewz lin894 views
Render Caching for Drupal 8 by John Doyle
Render Caching for Drupal 8Render Caching for Drupal 8
Render Caching for Drupal 8
John Doyle3.6K views
Little Did He Know ... by Burt Beckwith
Little Did He Know ...Little Did He Know ...
Little Did He Know ...
Burt Beckwith2.4K views
Oscon Java Testing on the Fast Lane by Andres Almiray
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
Andres Almiray3.9K views
Simple Pure Java by Anton Keks
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks8.6K views
Terence Barr - jdk7+8 - 24mai2011 by Agora Group
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
Agora Group420 views
Clojure made-simple - John Stevenson by JAX London
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
JAX London2.7K views
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant? by Dmitri Shiryaev
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?
Dmitri Shiryaev1.8K views

More from chibochibo

Tour of Apache PredictionIO in 10 Minutes by
Tour of Apache PredictionIO in 10 MinutesTour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 Minuteschibochibo
1K views27 slides
Crawler Commons by
Crawler CommonsCrawler Commons
Crawler Commonschibochibo
635 views19 slides
LocalStack by
LocalStackLocalStack
LocalStackchibochibo
2.6K views43 slides
Is spark streaming based on reactive streams? by
Is spark streaming based on reactive streams?Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?chibochibo
980 views42 slides
What is doobie? - database access for scala - by
What is doobie? - database access for scala -What is doobie? - database access for scala -
What is doobie? - database access for scala -chibochibo
1.4K views30 slides
Quartzでcronを範囲検索したい by
Quartzでcronを範囲検索したいQuartzでcronを範囲検索したい
Quartzでcronを範囲検索したいchibochibo
1.6K views19 slides

More from chibochibo(13)

Tour of Apache PredictionIO in 10 Minutes by chibochibo
Tour of Apache PredictionIO in 10 MinutesTour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 Minutes
chibochibo1K views
Crawler Commons by chibochibo
Crawler CommonsCrawler Commons
Crawler Commons
chibochibo635 views
LocalStack by chibochibo
LocalStackLocalStack
LocalStack
chibochibo2.6K views
Is spark streaming based on reactive streams? by chibochibo
Is spark streaming based on reactive streams?Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?
chibochibo980 views
What is doobie? - database access for scala - by chibochibo
What is doobie? - database access for scala -What is doobie? - database access for scala -
What is doobie? - database access for scala -
chibochibo1.4K views
Quartzでcronを範囲検索したい by chibochibo
Quartzでcronを範囲検索したいQuartzでcronを範囲検索したい
Quartzでcronを範囲検索したい
chibochibo1.6K views
ビッグじゃなくても使えるSpark Streaming by chibochibo
ビッグじゃなくても使えるSpark Streamingビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streaming
chibochibo3.4K views
nioで作ったBufferedWriterに変えたら例外になった by chibochibo
nioで作ったBufferedWriterに変えたら例外になったnioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になった
chibochibo5.5K views
Spark Streaming on AWS -S3からKinesisへ- by chibochibo
Spark Streaming on AWS -S3からKinesisへ-Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-
chibochibo1.1K views
Spark in small or middle scale data processing with Elasticsearch by chibochibo
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
chibochibo7.6K views
What's a macro?: Learning by Examples by chibochibo
What's a macro?: Learning by ExamplesWhat's a macro?: Learning by Examples
What's a macro?: Learning by Examples
chibochibo2.2K views
Spring Boot Introduction by chibochibo
Spring Boot IntroductionSpring Boot Introduction
Spring Boot Introduction
chibochibo2.3K views
Slick入門 by chibochibo
Slick入門Slick入門
Slick入門
chibochibo7.2K views

Recently uploaded

Post-event report intro session-1.docx by
Post-event report intro session-1.docxPost-event report intro session-1.docx
Post-event report intro session-1.docxRohitRathi59
12 views2 slides
PB CV by
PB CVPB CV
PB CVPedro Borracha
7 views16 slides
The Throne of Your Heart 11-26-23 PPT.pptx by
The Throne of Your Heart 11-26-23 PPT.pptxThe Throne of Your Heart 11-26-23 PPT.pptx
The Throne of Your Heart 11-26-23 PPT.pptxFamilyWorshipCenterD
5 views24 slides
OSMC 2023 | IGNITE: Metrics, Margins, Mutiny – How to make your SREs (not) ru... by
OSMC 2023 | IGNITE: Metrics, Margins, Mutiny – How to make your SREs (not) ru...OSMC 2023 | IGNITE: Metrics, Margins, Mutiny – How to make your SREs (not) ru...
OSMC 2023 | IGNITE: Metrics, Margins, Mutiny – How to make your SREs (not) ru...NETWAYS
8 views20 slides
BLogSite (Web Programming) (1).pdf by
BLogSite (Web Programming) (1).pdfBLogSite (Web Programming) (1).pdf
BLogSite (Web Programming) (1).pdfFiverr
11 views9 slides
Timeahead Agency Pitch Deck.pdf by
Timeahead Agency Pitch Deck.pdfTimeahead Agency Pitch Deck.pdf
Timeahead Agency Pitch Deck.pdfHabib-ur- Rehman
9 views13 slides

Recently uploaded(20)

Post-event report intro session-1.docx by RohitRathi59
Post-event report intro session-1.docxPost-event report intro session-1.docx
Post-event report intro session-1.docx
RohitRathi5912 views
OSMC 2023 | IGNITE: Metrics, Margins, Mutiny – How to make your SREs (not) ru... by NETWAYS
OSMC 2023 | IGNITE: Metrics, Margins, Mutiny – How to make your SREs (not) ru...OSMC 2023 | IGNITE: Metrics, Margins, Mutiny – How to make your SREs (not) ru...
OSMC 2023 | IGNITE: Metrics, Margins, Mutiny – How to make your SREs (not) ru...
NETWAYS8 views
BLogSite (Web Programming) (1).pdf by Fiverr
BLogSite (Web Programming) (1).pdfBLogSite (Web Programming) (1).pdf
BLogSite (Web Programming) (1).pdf
Fiverr11 views
Managing Github via Terrafom.pdf by micharaeck
Managing Github via Terrafom.pdfManaging Github via Terrafom.pdf
Managing Github via Terrafom.pdf
micharaeck5 views
Helko van den Brom - VSL by Dutch Power
Helko van den Brom - VSLHelko van den Brom - VSL
Helko van den Brom - VSL
Dutch Power86 views
OSMC | SNMP Monitoring at scale by Rocco Pezzani & Thomas Gelf by NETWAYS
OSMC | SNMP Monitoring at scale by Rocco Pezzani & Thomas Gelf OSMC | SNMP Monitoring at scale by Rocco Pezzani & Thomas Gelf
OSMC | SNMP Monitoring at scale by Rocco Pezzani & Thomas Gelf
NETWAYS15 views
Gym Members Community.pptx by nasserbf1987
Gym Members Community.pptxGym Members Community.pptx
Gym Members Community.pptx
nasserbf19876 views
Roozbeh Torkzadeh - TU Eindhoven by Dutch Power
Roozbeh Torkzadeh - TU EindhovenRoozbeh Torkzadeh - TU Eindhoven
Roozbeh Torkzadeh - TU Eindhoven
Dutch Power84 views
OSMC 2023 | Will ChatGPT Take Over My Job? by Philipp Krenn by NETWAYS
OSMC 2023 | Will ChatGPT Take Over My Job? by Philipp KrennOSMC 2023 | Will ChatGPT Take Over My Job? by Philipp Krenn
OSMC 2023 | Will ChatGPT Take Over My Job? by Philipp Krenn
NETWAYS22 views
231121 SP slides - PAS workshop November 2023.pdf by PAS_Team
231121 SP slides - PAS workshop November 2023.pdf231121 SP slides - PAS workshop November 2023.pdf
231121 SP slides - PAS workshop November 2023.pdf
PAS_Team156 views

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