Reputation: 159
I have been trying to understand how Kotlin coroutines work and I came across the delay
function.
My understanding of this works is,
delay
suspends the current thread, where the thread, unlike sleep
, does not consume CPU cycles and is freed to execute other tasks.delay
function causes the continuation to be stored on some kind of a task queue and releases the current thread. After the specified time is elapsed, this task is scheduled on an available thread.Is my understanding correct?
Also, is there a relation between the thread that calls delay
and the thread that executes the code following the call to delay
.
Thanks!
Upvotes: 8
Views: 1320
Reputation: 28648
Yes. Your understanding is correct. The difference between JS and Kotlin is that the task queue that is used to execute the continuation can be customized by the programmer via CoroutineDispatcher
. In general, there is no relation between the thread that calls delay
and the thread where continuation is scheduled for resume. It is determined by two factors:
If the coroutine uses the Unconfined
dispatcher, then the thread where the continuation is resumed is some system timer thread used internally in the implementation of delay
. You can write your own version of delay
that resumes Unconfined
continuations on the thread of your choice.
If the coroutine uses some confined dispatcher, then it resumes on the thread or a pool of threads defined by that dispatcher. A number of dispatchers are provided out of the box. For example, in Android using the UI
dispatcher, the coroutine is going to be always resumed on the Android UI
thread. In general, in Kotlin/JVM you can take any Executor
and convert it to CoroutineDispatcher
using asCoroutineDispatcher
extension.
Upvotes: 9