SlideShare a Scribd company logo
Kotlin Coroutine
Behind of the scenes
Anh Vu

tuananh.vu@foodycorp.vn

@anhvt52
Concurrency is not parallelism
Concurrency is about dealing with
lots of things at once
Concurrency is about dealing with
lots of things at once
Parallelism is about doing
lots of things at once
Go to office Input info Go back Do SliceQueue
Queue
Go to office Input info Go back
Do Slice
Do Slice
Go to office Input info Go back
Do Slice
Queue
Suspendable computation
Suspending function
Suspending function
Suspending function
Thread
Function B
Function A
Suspended
suspend fun backgroundTask(param: Int): Int {
// long running operation
}
suspend fun backgroundTask(param: Int): Int {
// long running operation
}
Continuation
interface Continuation<in T> {
val context: CoroutineContext
fun resumeWith(result: Result<T>)
}
fun <T> Continuation<T>.resume(value: T)
fun <T> Continuation<T>.resumeWithException(exception: Throwable)
suspend fun <T> CompletableFuture<T>.await(): T =
suspendCoroutine<T> { cont: Continuation<T> ->
whenComplete { result, exception ->
if (exception == null) // the future has been completed n
cont.resume(result)
else // the future has completed with an exception
cont.resumeWithException(exception)
}
}
}
Context Switching
Context Switching
Overhead
Thread Pool
Kotlin coroutine - behind the scenes
Coroutines
coroutineScope { // Creates a coroutine scope
launch { //coroutine builder
withContext(Dispatchers.IO) { //context switching
doABigTask() //execute task
}
}
}
suspend fun doABigTask() {
//…
}
Kotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenes
Coroutines are light-weight
Coroutines are light-weight
Coroutines are light-weight
fun main() = runBlocking {
repeat(100_000) { // launch a lot of coroutines
launch {
delay(1000L)
print(".")
}
}
}
Job and Deferred
Job and Deferred
fun CoroutineScope.launch(
context: CoroutineContext =
EmptyCoroutineContext,
// ...
): Job
Kotlin coroutine - behind the scenes
Coroutine Scope
Coroutine Scope
fun CoroutineScope.launch(
context: CoroutineContext =
EmptyCoroutineContext,
// ...
): Job
class MyActivity : AppCompatActivity(),
CoroutineScope by MainScope() {
override fun onDestroy() {
cancel() // cancel is extension on CoroutineScope
}
//...
}
public fun MainScope(): CoroutineScope
= ContextScope(SupervisorJob() + Dispatchers.Main)
Coroutine Context and
Dispatcher
launch {
// context of the parent, main runBlocking coroutine
println("main runBlocking: ${Thread.currentThread().name}")
}
launch(Dispatchers.Unconfined) {
// not confined -- will work with main thread
println("Unconfined: ${Thread.currentThread().name}")
}
launch(Dispatchers.Default) {
// will get dispatched to DefaultDispatcher
println("Default: ${Thread.currentThread().name}")
}
launch(newSingleThreadContext("MyOwnThread")) {
// will get its own new thread
println("newSingleThreadContext: ${Thread.currentThread().name}")
}
//sampleEnd
Internal of Coroutine
Continuation passing style
Continuation passing style
suspend fun <T> CompletableFuture<T>.await(): T
fun <T> CompletableFuture<T>.await(continuation: Continuation<T>): Any?
suspend fun postItem(item: Item) {
val token = requestToken()
val post = createPost(token, item)
processPost(post)
}
suspend fun requestToken() {
//..
}
supsend fun createPost(token: String, item: Item) {
//..
}
fun postItem(item: Item) {
requestToken { token ->
createPost(token, item) { post ->
processPost(post)
}
}
}
suspend fun postItem(item: Item) {
val token = requestToken()
val post = createPost(token, item)
processPost(post)
}
Callbacks
State machine
Labelling
suspend fun postItem(item: Item) {
// LABEL 0
val token = requestToken()
// LABEL 1
val post = createPost(token, item)
// LABEL 2
processPost(post)
}
Labelling
suspend fun postItem(item: Item) {
switch (label) {
case 0:
val token = requestToken()
case 1:
val post = createPost(token, item)
case 2:
processPost(post)
}
}
State
suspend fun postItem(item: Item) {
val sm = object : CoroutineImpl { … }
switch (label) {
case 0:
val token = requestToken()
case 1:
val post = createPost(token, item)
case 2:
processPost(post)
}
}
CPS transform
fun postItem(item: Item, cont: Continuation) {
val sm = object : CoroutineImpl { … }
switch (label) {
case 0:
val token = requestToken(sm)
case 1:
val post = createPost(token, item, sm)
case 2:
processPost(post)
}
}
Store state
fun postItem(item: Item,cont: Continuation) {
val sm = object : CoroutineImpl { … }
switch (label) {
case 0:
sm.item = item
sm.label = 1
val token = requestToken(sm)
case 1:
//...
}
}
Store state
fun postItem(item: Item, cont: Continuation) {
val sm = object : CoroutineImpl {
fun resume(…) {
postItem(null, this)
}
}
switch (label) {
case 0:
sm.item = item
sm.label = 1
val token = requestToken(sm)
case 1:
//...
}
}
Restore state
fun postItem(item: Item,cont: Continuation) {
val sm = ..
switch (label) {
case 0:
//...
case 1:
val item = sm.item
val token = sm.result as Token
sm.label = 2
createPost(token, item, sm)
//...
}
}
State machine vs Callbacks
fun postItem(item: Item) {
requestToken { token ->
createPost(token, item) { post ->
processPost(post)
}
}
}
suspend fun postItem(item: Item) {
val token = requestToken()
val post = createPost(token, item)
processPost(post)
}
Callbacks
Q&A

More Related Content

What's hot (20)

PDF
Network programming Using Python
Karim Sonbol
 
PPT
JDBC
Sunil OS
 
PPT
Java naming conventions
Lovely Professional University
 
PPTX
class and objects
Payel Guria
 
PPTX
Introduction to java 8 stream api
Vladislav sidlyarevich
 
PPT
Java RMI
Sunil OS
 
PDF
Java String
Java2Blog
 
PPT
Java Input Output and File Handling
Sunil OS
 
PPTX
MongoDB Aggregations Indexing and Profiling
Manish Kapoor
 
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
DOCX
Autoboxing and unboxing
Geetha Manohar
 
PPT
Java 8 - CJ
Sunil OS
 
PPTX
Hibernate ppt
Aneega
 
PPTX
Java Stack Data Structure.pptx
vishal choudhary
 
PDF
Wrapper classes
Ravi_Kant_Sahu
 
PPTX
classes and objects in C++
HalaiHansaika
 
PPT
Serialization/deserialization
Young Alista
 
PPTX
Understanding java streams
Shahjahan Samoon
 
ODP
Java Collections
parag
 
PPTX
String in java
Ideal Eyes Business College
 
Network programming Using Python
Karim Sonbol
 
JDBC
Sunil OS
 
Java naming conventions
Lovely Professional University
 
class and objects
Payel Guria
 
Introduction to java 8 stream api
Vladislav sidlyarevich
 
Java RMI
Sunil OS
 
Java String
Java2Blog
 
Java Input Output and File Handling
Sunil OS
 
MongoDB Aggregations Indexing and Profiling
Manish Kapoor
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Autoboxing and unboxing
Geetha Manohar
 
Java 8 - CJ
Sunil OS
 
Hibernate ppt
Aneega
 
Java Stack Data Structure.pptx
vishal choudhary
 
Wrapper classes
Ravi_Kant_Sahu
 
classes and objects in C++
HalaiHansaika
 
Serialization/deserialization
Young Alista
 
Understanding java streams
Shahjahan Samoon
 
Java Collections
parag
 

Similar to Kotlin coroutine - behind the scenes (20)

PDF
Deep dive into Coroutines on JVM @ KotlinConf 2017
Roman Elizarov
 
PDF
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
PDF
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
PDF
Introduction to Coroutines @ KotlinConf 2017
Roman Elizarov
 
PDF
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
NAVER Engineering
 
PDF
Dive into kotlins coroutines
Freddie Wang
 
PDF
Kotlin Coroutines Reloaded
Roman Elizarov
 
PDF
Fresh Async with Kotlin @ QConSF 2017
Roman Elizarov
 
PDF
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
PDF
Dip into Coroutines - KTUG Munich 202303
Alex Semin
 
PDF
Kotlin - Coroutine
Sean Tsai
 
PDF
Kotlin의 코루틴은 어떻게 동작하는가
Chang W. Doh
 
PDF
Kotlin : Advanced Tricks - Ubiratan Soares
iMasters
 
PDF
Current State of Coroutines
Guido Pio Mariotti
 
PPTX
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
Karel Zikmund
 
PPTX
2019-01-29 - Demystifying Kotlin Coroutines
Eamonn Boyle
 
PDF
Kotlin Coroutines. Flow is coming
Kirill Rozov
 
PDF
Kotlin Coroutines - the new async
Bartłomiej Osmałek
 
PPT
Orsiso
e27
 
PPTX
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Karel Zikmund
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Roman Elizarov
 
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Introduction to Coroutines @ KotlinConf 2017
Roman Elizarov
 
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
NAVER Engineering
 
Dive into kotlins coroutines
Freddie Wang
 
Kotlin Coroutines Reloaded
Roman Elizarov
 
Fresh Async with Kotlin @ QConSF 2017
Roman Elizarov
 
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
Dip into Coroutines - KTUG Munich 202303
Alex Semin
 
Kotlin - Coroutine
Sean Tsai
 
Kotlin의 코루틴은 어떻게 동작하는가
Chang W. Doh
 
Kotlin : Advanced Tricks - Ubiratan Soares
iMasters
 
Current State of Coroutines
Guido Pio Mariotti
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
Karel Zikmund
 
2019-01-29 - Demystifying Kotlin Coroutines
Eamonn Boyle
 
Kotlin Coroutines. Flow is coming
Kirill Rozov
 
Kotlin Coroutines - the new async
Bartłomiej Osmałek
 
Orsiso
e27
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Karel Zikmund
 
Ad

Recently uploaded (20)

PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Python basic programing language for automation
DanialHabibi2
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Ad

Kotlin coroutine - behind the scenes