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 (15)

PDF
Garbage collector in python
Ibrahim Kasim
 
PDF
Handle Large Messages In Apache Kafka
Jiangjie Qin
 
PPT
Watir
Sai Venkat
 
PDF
Stream Processing with Apache Flink
C4Media
 
PDF
Introduction to Kotlin coroutines
Roman Elizarov
 
PDF
Introduction to Coroutines @ KotlinConf 2017
Roman Elizarov
 
PPTX
ZIO: Powerful and Principled Functional Programming in Scala
Wiem Zine Elabidine
 
PDF
OOP Best Practices in JavaScript
Haim Michael
 
KEY
ElasticSearch at berlinbuzzwords 2010
Elasticsearch
 
PDF
Domain Driven Design with the F# type System -- NDC London 2013
Scott Wlaschin
 
PPTX
Extending Flink SQL for stream processing use cases
Flink Forward
 
PDF
Best Practices for ETL with Apache NiFi on Kubernetes - Albert Lewandowski, G...
GetInData
 
PDF
GraphQL IN Golang
Bo-Yi Wu
 
PDF
Helpful logging with python
roskakori
 
PPTX
Welcome to the Flink Community!
Flink Forward
 
Garbage collector in python
Ibrahim Kasim
 
Handle Large Messages In Apache Kafka
Jiangjie Qin
 
Watir
Sai Venkat
 
Stream Processing with Apache Flink
C4Media
 
Introduction to Kotlin coroutines
Roman Elizarov
 
Introduction to Coroutines @ KotlinConf 2017
Roman Elizarov
 
ZIO: Powerful and Principled Functional Programming in Scala
Wiem Zine Elabidine
 
OOP Best Practices in JavaScript
Haim Michael
 
ElasticSearch at berlinbuzzwords 2010
Elasticsearch
 
Domain Driven Design with the F# type System -- NDC London 2013
Scott Wlaschin
 
Extending Flink SQL for stream processing use cases
Flink Forward
 
Best Practices for ETL with Apache NiFi on Kubernetes - Albert Lewandowski, G...
GetInData
 
GraphQL IN Golang
Bo-Yi Wu
 
Helpful logging with python
roskakori
 
Welcome to the Flink Community!
Flink Forward
 

Similar to Kotlin coroutine - behind the scenes (20)

PDF
Deep dive into Coroutines on JVM @ KotlinConf 2017
Roman Elizarov
 
PDF
Fresh Async with Kotlin
C4Media
 
PDF
Fresh Async with Kotlin @ QConSF 2017
Roman Elizarov
 
PDF
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
PDF
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
PDF
Introduction to kotlin coroutines
NAVER Engineering
 
PDF
Dive into kotlins coroutines
Freddie Wang
 
PDF
Quick Introduction to Kotlin Coroutine for Android Dev
Shuhei Shogen
 
PDF
Tackling Asynchrony with Kotlin Coroutines
Tech Triveni
 
PPTX
Coroutines talk ppt
Shahroz Khan
 
PDF
Should it be routine to use coroutines?
Ion Stefan Brosteanu
 
PDF
Kotlin - Coroutine
Sean Tsai
 
PDF
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
PDF
Dip into Coroutines - KTUG Munich 202303
Alex Semin
 
PDF
Coroutines
Sevil Güler
 
PDF
Programação assíncrona utilizando Coroutines
Diego Gonçalves Santos
 
PDF
Coroutines in Kotlin
Dmytro Zaitsev
 
PDF
Current State of Coroutines
Guido Pio Mariotti
 
PPTX
2019-01-29 - Demystifying Kotlin Coroutines
Eamonn Boyle
 
PPTX
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Roman Elizarov
 
Fresh Async with Kotlin
C4Media
 
Fresh Async with Kotlin @ QConSF 2017
Roman Elizarov
 
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Introduction to kotlin coroutines
NAVER Engineering
 
Dive into kotlins coroutines
Freddie Wang
 
Quick Introduction to Kotlin Coroutine for Android Dev
Shuhei Shogen
 
Tackling Asynchrony with Kotlin Coroutines
Tech Triveni
 
Coroutines talk ppt
Shahroz Khan
 
Should it be routine to use coroutines?
Ion Stefan Brosteanu
 
Kotlin - Coroutine
Sean Tsai
 
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
Dip into Coroutines - KTUG Munich 202303
Alex Semin
 
Coroutines
Sevil Güler
 
Programação assíncrona utilizando Coroutines
Diego Gonçalves Santos
 
Coroutines in Kotlin
Dmytro Zaitsev
 
Current State of Coroutines
Guido Pio Mariotti
 
2019-01-29 - Demystifying Kotlin Coroutines
Eamonn Boyle
 
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
Ad

Recently uploaded (20)

PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Home Cleaning App Development Services.pdf
V3cube
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pdf
ghjghvhjgc
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Home Cleaning App Development Services.pdf
V3cube
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pdf
ghjghvhjgc
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
Ad

Kotlin coroutine - behind the scenes