Hi everyone, I have a question to check if my unde...
# coroutines
h
Hi everyone, I have a question to check if my understanding of
coroutine
is correct. When a coroutine hit a suspension point (like an
await()
call), it is paused from the thread that it was called from (depend on the
Dispatcher
), so that the thread can continue execute other codes and then the excution of the function that calls
await()
in the
coroutine
if offloaded to another thread in the `Dispatcher`'s thread pool? Thanks in advance
s
You're right about the first part. Yes, when a coroutine hits a suspension point, it vacates the thread, so the thread can continue to execute other code. But when a function like
await()
suspends its coroutine, it's no longer executing any code, so the second part of your message isn't quite right. The call to
await()
doesn't need to offload anything to other threads in its dispatcher's thread pool. Instead, the task/event that it's waiting for is responsible for its own execution, and will notify the suspended coroutine when it's time to resume.
h
Thanks for the answer. I'm still somewhat confused how does the coroutine "know" there is no more code to execute so that it can enter the pause state, like when a db
connection
do a
executeQuery
call inside a suspension function, how does the couroutine know where is the suspension point so it can vacate the thread?
s
Suspension points are always explicit instructions in the code. If you just call a regular function like JDBC's
Statement.executeQuery()
, that function doesn't contain any suspension points, and so the coroutine would never be able to vacate the thread. There are two options to fix that: 1. Use a different function. It could be one that's written with suspension points from the ground up, or it could be written with asynchronous callbacks/futures that are converted into a suspension point. 2. Use
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {…}
to offload the query to a designated I/O thread. This lets the caller suspend (i.e. vacate its thread) while it waits for the code inside the
withContext
block to be executed. Maybe this is similar to what you were imagining in your original question.
If you dig down inside a suspending function, you'll eventually find it calls a function like
suspendCoroutine
or
suspendCancellableCoroutine
, which is the explicit instruction that tells the coroutine to enter that paused state you were describing.
h
Thanks for the answer, Sam. I’ll check on the
suspendCoroutine
🙂