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

JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
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 CoffeeScriptroyaldark
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScriptMathieu Breton
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - TryoutMatthias Noback
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 
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...go_oh
 
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 & UXJWORKS powered by Ordina
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyスローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyYusuke Yamamoto
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby.toster
 

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.jstakezoe
 
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 #ScalaMatsuriTIS Inc.
 
Make your programs Free
Make your programs FreeMake your programs Free
Make your programs FreePawel Szulc
 
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 ExampleConnie Chen
 
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 WorldKonrad Malawski
 
7 key recipes for data engineering
7 key recipes for data engineering7 key recipes for data engineering
7 key recipes for data engineeringunivalence
 
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 typesPawel Szulc
 
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~
Dockerの期待と現実~Docker都市伝説はなぜ生まれるのか~Masahito Zembutsu
 
Akka Cluster and Auto-scaling
Akka Cluster and Auto-scalingAkka Cluster and Auto-scaling
Akka Cluster and Auto-scalingIkuo Matsumura
 
Van laarhoven lens
Van laarhoven lensVan laarhoven lens
Van laarhoven lensNaoki Aoyama
 
Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka StreamsKonrad Malawski
 
Dynamic SQL in doobie
Dynamic SQL in doobieDynamic SQL in doobie
Dynamic SQL in doobiechibochibo
 
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)Eugene Yokota
 
Tracing Microservices with Zipkin
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkintakezoe
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShareSlideShare
 
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 AWSAmazon Web Services
 
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 storesTomas Doran
 
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...Jonathan Gray
 

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

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 OredevMattias Karlsson
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaoladrewz lin
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Render Caching for Drupal 8
Render Caching for Drupal 8Render Caching for Drupal 8
Render Caching for Drupal 8John Doyle
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...Burt Beckwith
 
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 LaneAndres Almiray
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure JavaAnton Keks
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Agora Group
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021Thodoris Bais
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
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?Dmitri Shiryaev
 

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

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 Minuteschibochibo
 
Crawler Commons
Crawler CommonsCrawler Commons
Crawler Commonschibochibo
 
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?chibochibo
 
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 -chibochibo
 
Quartzでcronを範囲検索したい
Quartzでcronを範囲検索したいQuartzでcronを範囲検索したい
Quartzでcronを範囲検索したいchibochibo
 
ビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streamingビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streamingchibochibo
 
nioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になったnioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になったchibochibo
 
Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-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 Elasticsearchchibochibo
 
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 Exampleschibochibo
 
Spring Boot Introduction
Spring Boot IntroductionSpring Boot Introduction
Spring Boot Introductionchibochibo
 

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

05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptxerickamwana1
 
Sunlight Spectacle 2024 Practical Action Launch Event 2024-04-08
Sunlight Spectacle 2024 Practical Action Launch Event 2024-04-08Sunlight Spectacle 2024 Practical Action Launch Event 2024-04-08
Sunlight Spectacle 2024 Practical Action Launch Event 2024-04-08LloydHelferty
 
Scootsy Overview Deck - Pan City Delivery
Scootsy Overview Deck - Pan City DeliveryScootsy Overview Deck - Pan City Delivery
Scootsy Overview Deck - Pan City Deliveryrishi338139
 
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunityDon't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunityApp Ethena
 
Understanding Post Production changes (PPC) in Clinical Data Management (CDM)...
Understanding Post Production changes (PPC) in Clinical Data Management (CDM)...Understanding Post Production changes (PPC) in Clinical Data Management (CDM)...
Understanding Post Production changes (PPC) in Clinical Data Management (CDM)...soumyapottola
 
General Elections Final Press Noteas per M
General Elections Final Press Noteas per MGeneral Elections Final Press Noteas per M
General Elections Final Press Noteas per MVidyaAdsule1
 
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...Sebastiano Panichella
 
GESCO SE Press and Analyst Conference on Financial Results 2024
GESCO SE Press and Analyst Conference on Financial Results 2024GESCO SE Press and Analyst Conference on Financial Results 2024
GESCO SE Press and Analyst Conference on Financial Results 2024GESCO SE
 
cse-csp batch4 review-1.1.pptx cyber security
cse-csp batch4 review-1.1.pptx cyber securitycse-csp batch4 review-1.1.pptx cyber security
cse-csp batch4 review-1.1.pptx cyber securitysandeepnani2260
 
Application of GIS in Landslide Disaster Response.pptx
Application of GIS in Landslide Disaster Response.pptxApplication of GIS in Landslide Disaster Response.pptx
Application of GIS in Landslide Disaster Response.pptxRoquia Salam
 
Testing with Fewer Resources: Toward Adaptive Approaches for Cost-effective ...
Testing with Fewer Resources:  Toward Adaptive Approaches for Cost-effective ...Testing with Fewer Resources:  Toward Adaptive Approaches for Cost-effective ...
Testing with Fewer Resources: Toward Adaptive Approaches for Cost-effective ...Sebastiano Panichella
 

Recently uploaded (11)

05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
 
Sunlight Spectacle 2024 Practical Action Launch Event 2024-04-08
Sunlight Spectacle 2024 Practical Action Launch Event 2024-04-08Sunlight Spectacle 2024 Practical Action Launch Event 2024-04-08
Sunlight Spectacle 2024 Practical Action Launch Event 2024-04-08
 
Scootsy Overview Deck - Pan City Delivery
Scootsy Overview Deck - Pan City DeliveryScootsy Overview Deck - Pan City Delivery
Scootsy Overview Deck - Pan City Delivery
 
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunityDon't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
 
Understanding Post Production changes (PPC) in Clinical Data Management (CDM)...
Understanding Post Production changes (PPC) in Clinical Data Management (CDM)...Understanding Post Production changes (PPC) in Clinical Data Management (CDM)...
Understanding Post Production changes (PPC) in Clinical Data Management (CDM)...
 
General Elections Final Press Noteas per M
General Elections Final Press Noteas per MGeneral Elections Final Press Noteas per M
General Elections Final Press Noteas per M
 
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
 
GESCO SE Press and Analyst Conference on Financial Results 2024
GESCO SE Press and Analyst Conference on Financial Results 2024GESCO SE Press and Analyst Conference on Financial Results 2024
GESCO SE Press and Analyst Conference on Financial Results 2024
 
cse-csp batch4 review-1.1.pptx cyber security
cse-csp batch4 review-1.1.pptx cyber securitycse-csp batch4 review-1.1.pptx cyber security
cse-csp batch4 review-1.1.pptx cyber security
 
Application of GIS in Landslide Disaster Response.pptx
Application of GIS in Landslide Disaster Response.pptxApplication of GIS in Landslide Disaster Response.pptx
Application of GIS in Landslide Disaster Response.pptx
 
Testing with Fewer Resources: Toward Adaptive Approaches for Cost-effective ...
Testing with Fewer Resources:  Toward Adaptive Approaches for Cost-effective ...Testing with Fewer Resources:  Toward Adaptive Approaches for Cost-effective ...
Testing with Fewer Resources: Toward Adaptive Approaches for Cost-effective ...
 

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