Does Kotlin delay use a dispatcher internally to unblock the caller thread?In Kotlin, is it possible to change delegation at Runtime?Difference between thread and coroutine in KotlinHow does the delay function in Kotlin internally work?Kotlin coroutine async with delayWhen should I make my normal function suspending function?How do Kotlin coroutines work internally?Coroutines: runBlocking vs coroutineScopeIs NetworkOnMainThreadException valid for a network call in a coroutine?How to achieve non blocking with CoroutinesBasic coroutine network call in a library
Displaying an Estimated Execution Plan generates CXPACKET, PAGELATCH_SH, and LATCH_EX [ACCESS_METHODS_DATASET_PARENT] waits
Antivirus for Ubuntu 18.04
Gift for mentor after his thesis defense?
Employee is self-centered and affects the team negatively
Drug Testing and Prescribed Medications
Can you just subtract the challenge rating of friendly NPCs?
What detail can Hubble see on Mars?
Why doesn't a particle exert force on itself?
What did Varys actually mean?
Does restarting the SQL Services (on the machine) clear the server cache (for things like query plans and statistics)?
Why did Gendry call himself Gendry Rivers?
What's the 2-minute timer on mobile Deutsche Bahn tickets?
A♭ major 9th chord in Bach is unexpectedly dissonant/jazzy
Picking a theme as a discovery writer
And now you see it
Searching for a sentence that I only know part of it using Google's operators
Justification of physical currency in an interstellar civilization?
If an attacker targets a creature with the Sanctuary spell cast on them, but fails the Wisdom save, can they choose not to attack anyone else?
Why is the blank symbol not considered part of the input alphabet of a Turing machine?
Why were the rules for Proliferate changed?
What is the Ancient One's mistake?
Scaling rounded rectangles in Illustrator
How can I finally understand the confusing modal verb "мочь"?
Was there a dinosaur-counter in the original Jurassic Park movie?
Does Kotlin delay use a dispatcher internally to unblock the caller thread?
In Kotlin, is it possible to change delegation at Runtime?Difference between thread and coroutine in KotlinHow does the delay function in Kotlin internally work?Kotlin coroutine async with delayWhen should I make my normal function suspending function?How do Kotlin coroutines work internally?Coroutines: runBlocking vs coroutineScopeIs NetworkOnMainThreadException valid for a network call in a coroutine?How to achieve non blocking with CoroutinesBasic coroutine network call in a library
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
This is some test code I am using to learn kotlin coroutines. The code works as expected and takes about 1 Second to print the sum, but now If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum ( each call takes around 1 second), but if I wrap the network call in a withContext and use the IO dispatcher it takes 1 second to print the sum, because it is run on a different thread. Does the delay function use some kind of a dispatcher to unblock the thread?
suspend fun asyncDoubleFn(num: Int): Int
delay(1000)
return num * 2
fun main() = runBlocking
launch
val tt = measureTimeMillis
val results = mutableListOf<Deferred<Int>>()
for (num in 0..10)
val result = async asyncDoubleFn(num + 1)
results.add(result)
val sum = results.map it.await() .reduce acc, i -> acc + i
println("[SUM]: $sum")
println("[TT]: $tt")
launch
println("Another coroutine")
println("Main Code")
kotlin kotlin-coroutines
add a comment |
This is some test code I am using to learn kotlin coroutines. The code works as expected and takes about 1 Second to print the sum, but now If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum ( each call takes around 1 second), but if I wrap the network call in a withContext and use the IO dispatcher it takes 1 second to print the sum, because it is run on a different thread. Does the delay function use some kind of a dispatcher to unblock the thread?
suspend fun asyncDoubleFn(num: Int): Int
delay(1000)
return num * 2
fun main() = runBlocking
launch
val tt = measureTimeMillis
val results = mutableListOf<Deferred<Int>>()
for (num in 0..10)
val result = async asyncDoubleFn(num + 1)
results.add(result)
val sum = results.map it.await() .reduce acc, i -> acc + i
println("[SUM]: $sum")
println("[TT]: $tt")
launch
println("Another coroutine")
println("Main Code")
kotlin kotlin-coroutines
Source: github.com/Kotlin/kotlinx.coroutines/blob/master/common/…
– Moira
Mar 23 at 8:32
Thanks! I was looking for a little detailed explanation , since I am new to this concept, but am familiar with JS async await(Mostly do front-end JS). I mainly want to understand if we can take a blocking API like java.net.URL and run it in suspend mode.
– Shubhang B
Mar 23 at 9:28
You can, take a look atsuspendCoroutine
. I'm not familiar enough with the details to fully explain how it works, but there was a good talk on this at KotlinConf.
– Moira
Mar 23 at 9:31
add a comment |
This is some test code I am using to learn kotlin coroutines. The code works as expected and takes about 1 Second to print the sum, but now If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum ( each call takes around 1 second), but if I wrap the network call in a withContext and use the IO dispatcher it takes 1 second to print the sum, because it is run on a different thread. Does the delay function use some kind of a dispatcher to unblock the thread?
suspend fun asyncDoubleFn(num: Int): Int
delay(1000)
return num * 2
fun main() = runBlocking
launch
val tt = measureTimeMillis
val results = mutableListOf<Deferred<Int>>()
for (num in 0..10)
val result = async asyncDoubleFn(num + 1)
results.add(result)
val sum = results.map it.await() .reduce acc, i -> acc + i
println("[SUM]: $sum")
println("[TT]: $tt")
launch
println("Another coroutine")
println("Main Code")
kotlin kotlin-coroutines
This is some test code I am using to learn kotlin coroutines. The code works as expected and takes about 1 Second to print the sum, but now If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum ( each call takes around 1 second), but if I wrap the network call in a withContext and use the IO dispatcher it takes 1 second to print the sum, because it is run on a different thread. Does the delay function use some kind of a dispatcher to unblock the thread?
suspend fun asyncDoubleFn(num: Int): Int
delay(1000)
return num * 2
fun main() = runBlocking
launch
val tt = measureTimeMillis
val results = mutableListOf<Deferred<Int>>()
for (num in 0..10)
val result = async asyncDoubleFn(num + 1)
results.add(result)
val sum = results.map it.await() .reduce acc, i -> acc + i
println("[SUM]: $sum")
println("[TT]: $tt")
launch
println("Another coroutine")
println("Main Code")
kotlin kotlin-coroutines
kotlin kotlin-coroutines
asked Mar 23 at 6:07
Shubhang BShubhang B
3213
3213
Source: github.com/Kotlin/kotlinx.coroutines/blob/master/common/…
– Moira
Mar 23 at 8:32
Thanks! I was looking for a little detailed explanation , since I am new to this concept, but am familiar with JS async await(Mostly do front-end JS). I mainly want to understand if we can take a blocking API like java.net.URL and run it in suspend mode.
– Shubhang B
Mar 23 at 9:28
You can, take a look atsuspendCoroutine
. I'm not familiar enough with the details to fully explain how it works, but there was a good talk on this at KotlinConf.
– Moira
Mar 23 at 9:31
add a comment |
Source: github.com/Kotlin/kotlinx.coroutines/blob/master/common/…
– Moira
Mar 23 at 8:32
Thanks! I was looking for a little detailed explanation , since I am new to this concept, but am familiar with JS async await(Mostly do front-end JS). I mainly want to understand if we can take a blocking API like java.net.URL and run it in suspend mode.
– Shubhang B
Mar 23 at 9:28
You can, take a look atsuspendCoroutine
. I'm not familiar enough with the details to fully explain how it works, but there was a good talk on this at KotlinConf.
– Moira
Mar 23 at 9:31
Source: github.com/Kotlin/kotlinx.coroutines/blob/master/common/…
– Moira
Mar 23 at 8:32
Source: github.com/Kotlin/kotlinx.coroutines/blob/master/common/…
– Moira
Mar 23 at 8:32
Thanks! I was looking for a little detailed explanation , since I am new to this concept, but am familiar with JS async await(Mostly do front-end JS). I mainly want to understand if we can take a blocking API like java.net.URL and run it in suspend mode.
– Shubhang B
Mar 23 at 9:28
Thanks! I was looking for a little detailed explanation , since I am new to this concept, but am familiar with JS async await(Mostly do front-end JS). I mainly want to understand if we can take a blocking API like java.net.URL and run it in suspend mode.
– Shubhang B
Mar 23 at 9:28
You can, take a look at
suspendCoroutine
. I'm not familiar enough with the details to fully explain how it works, but there was a good talk on this at KotlinConf.– Moira
Mar 23 at 9:31
You can, take a look at
suspendCoroutine
. I'm not familiar enough with the details to fully explain how it works, but there was a good talk on this at KotlinConf.– Moira
Mar 23 at 9:31
add a comment |
1 Answer
1
active
oldest
votes
Does the delay function use some kind of a dispatcher to unblock the thread?
Not just delay
. All suspendable functions interact with the dispatcher.
The question you should ask is: "Which dispatcher is in charge here?"
And the answer is: runBlocking
installs its own dispatcher that dispatches to the thread it is called on. Both launch
and async
in your code inherit it.
With this in mind:
If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum (each call takes around 1 second)
Each blocking call will hold on to the single thread of the dispatcher. It won't be able to do any other work while being blocked.
but if I wrap the network call in a
withContext
and use theIO
dispatcher it takes 1 second to print the sum, because it is run on a different thread
Yes, this changes the dispatcher, problem solved.
So, what does delay
do? It suspends the current coroutine (the one that async
launched) and returns the control to the dispatcher, which can now go on to resume your loop and start the next coroutine.
Thank you for the detailed answer, this clears most of my confusion, you said delay suspends the current coroutine and returns control to the dispatcher, does delay use some kind of a task queue scheduling to run the code after the delay time elapses , does it work like setTimeout in JS?.
– Shubhang B
Mar 24 at 13:55
1
It works pretty much exactly like that. TherunBlocking
dispatcher establishes an event queue and an event loop that drains the queue and handles the events. Just like the Android looper or the Swing event loop or the JS event loop.
– Marko Topolnik
Mar 25 at 7:34
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55311103%2fdoes-kotlin-delay-use-a-dispatcher-internally-to-unblock-the-caller-thread%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Does the delay function use some kind of a dispatcher to unblock the thread?
Not just delay
. All suspendable functions interact with the dispatcher.
The question you should ask is: "Which dispatcher is in charge here?"
And the answer is: runBlocking
installs its own dispatcher that dispatches to the thread it is called on. Both launch
and async
in your code inherit it.
With this in mind:
If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum (each call takes around 1 second)
Each blocking call will hold on to the single thread of the dispatcher. It won't be able to do any other work while being blocked.
but if I wrap the network call in a
withContext
and use theIO
dispatcher it takes 1 second to print the sum, because it is run on a different thread
Yes, this changes the dispatcher, problem solved.
So, what does delay
do? It suspends the current coroutine (the one that async
launched) and returns the control to the dispatcher, which can now go on to resume your loop and start the next coroutine.
Thank you for the detailed answer, this clears most of my confusion, you said delay suspends the current coroutine and returns control to the dispatcher, does delay use some kind of a task queue scheduling to run the code after the delay time elapses , does it work like setTimeout in JS?.
– Shubhang B
Mar 24 at 13:55
1
It works pretty much exactly like that. TherunBlocking
dispatcher establishes an event queue and an event loop that drains the queue and handles the events. Just like the Android looper or the Swing event loop or the JS event loop.
– Marko Topolnik
Mar 25 at 7:34
add a comment |
Does the delay function use some kind of a dispatcher to unblock the thread?
Not just delay
. All suspendable functions interact with the dispatcher.
The question you should ask is: "Which dispatcher is in charge here?"
And the answer is: runBlocking
installs its own dispatcher that dispatches to the thread it is called on. Both launch
and async
in your code inherit it.
With this in mind:
If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum (each call takes around 1 second)
Each blocking call will hold on to the single thread of the dispatcher. It won't be able to do any other work while being blocked.
but if I wrap the network call in a
withContext
and use theIO
dispatcher it takes 1 second to print the sum, because it is run on a different thread
Yes, this changes the dispatcher, problem solved.
So, what does delay
do? It suspends the current coroutine (the one that async
launched) and returns the control to the dispatcher, which can now go on to resume your loop and start the next coroutine.
Thank you for the detailed answer, this clears most of my confusion, you said delay suspends the current coroutine and returns control to the dispatcher, does delay use some kind of a task queue scheduling to run the code after the delay time elapses , does it work like setTimeout in JS?.
– Shubhang B
Mar 24 at 13:55
1
It works pretty much exactly like that. TherunBlocking
dispatcher establishes an event queue and an event loop that drains the queue and handles the events. Just like the Android looper or the Swing event loop or the JS event loop.
– Marko Topolnik
Mar 25 at 7:34
add a comment |
Does the delay function use some kind of a dispatcher to unblock the thread?
Not just delay
. All suspendable functions interact with the dispatcher.
The question you should ask is: "Which dispatcher is in charge here?"
And the answer is: runBlocking
installs its own dispatcher that dispatches to the thread it is called on. Both launch
and async
in your code inherit it.
With this in mind:
If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum (each call takes around 1 second)
Each blocking call will hold on to the single thread of the dispatcher. It won't be able to do any other work while being blocked.
but if I wrap the network call in a
withContext
and use theIO
dispatcher it takes 1 second to print the sum, because it is run on a different thread
Yes, this changes the dispatcher, problem solved.
So, what does delay
do? It suspends the current coroutine (the one that async
launched) and returns the control to the dispatcher, which can now go on to resume your loop and start the next coroutine.
Does the delay function use some kind of a dispatcher to unblock the thread?
Not just delay
. All suspendable functions interact with the dispatcher.
The question you should ask is: "Which dispatcher is in charge here?"
And the answer is: runBlocking
installs its own dispatcher that dispatches to the thread it is called on. Both launch
and async
in your code inherit it.
With this in mind:
If I replace delay(1000) by a blocking call like a network request, then the code takes about 10 seconds to print the sum (each call takes around 1 second)
Each blocking call will hold on to the single thread of the dispatcher. It won't be able to do any other work while being blocked.
but if I wrap the network call in a
withContext
and use theIO
dispatcher it takes 1 second to print the sum, because it is run on a different thread
Yes, this changes the dispatcher, problem solved.
So, what does delay
do? It suspends the current coroutine (the one that async
launched) and returns the control to the dispatcher, which can now go on to resume your loop and start the next coroutine.
answered Mar 24 at 7:31
Marko TopolnikMarko Topolnik
149k19201332
149k19201332
Thank you for the detailed answer, this clears most of my confusion, you said delay suspends the current coroutine and returns control to the dispatcher, does delay use some kind of a task queue scheduling to run the code after the delay time elapses , does it work like setTimeout in JS?.
– Shubhang B
Mar 24 at 13:55
1
It works pretty much exactly like that. TherunBlocking
dispatcher establishes an event queue and an event loop that drains the queue and handles the events. Just like the Android looper or the Swing event loop or the JS event loop.
– Marko Topolnik
Mar 25 at 7:34
add a comment |
Thank you for the detailed answer, this clears most of my confusion, you said delay suspends the current coroutine and returns control to the dispatcher, does delay use some kind of a task queue scheduling to run the code after the delay time elapses , does it work like setTimeout in JS?.
– Shubhang B
Mar 24 at 13:55
1
It works pretty much exactly like that. TherunBlocking
dispatcher establishes an event queue and an event loop that drains the queue and handles the events. Just like the Android looper or the Swing event loop or the JS event loop.
– Marko Topolnik
Mar 25 at 7:34
Thank you for the detailed answer, this clears most of my confusion, you said delay suspends the current coroutine and returns control to the dispatcher, does delay use some kind of a task queue scheduling to run the code after the delay time elapses , does it work like setTimeout in JS?.
– Shubhang B
Mar 24 at 13:55
Thank you for the detailed answer, this clears most of my confusion, you said delay suspends the current coroutine and returns control to the dispatcher, does delay use some kind of a task queue scheduling to run the code after the delay time elapses , does it work like setTimeout in JS?.
– Shubhang B
Mar 24 at 13:55
1
1
It works pretty much exactly like that. The
runBlocking
dispatcher establishes an event queue and an event loop that drains the queue and handles the events. Just like the Android looper or the Swing event loop or the JS event loop.– Marko Topolnik
Mar 25 at 7:34
It works pretty much exactly like that. The
runBlocking
dispatcher establishes an event queue and an event loop that drains the queue and handles the events. Just like the Android looper or the Swing event loop or the JS event loop.– Marko Topolnik
Mar 25 at 7:34
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55311103%2fdoes-kotlin-delay-use-a-dispatcher-internally-to-unblock-the-caller-thread%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Source: github.com/Kotlin/kotlinx.coroutines/blob/master/common/…
– Moira
Mar 23 at 8:32
Thanks! I was looking for a little detailed explanation , since I am new to this concept, but am familiar with JS async await(Mostly do front-end JS). I mainly want to understand if we can take a blocking API like java.net.URL and run it in suspend mode.
– Shubhang B
Mar 23 at 9:28
You can, take a look at
suspendCoroutine
. I'm not familiar enough with the details to fully explain how it works, but there was a good talk on this at KotlinConf.– Moira
Mar 23 at 9:31