I am new to Android Coroutines. I've been reading about it from the official docs and found this note
Important: Using a dispatcher that uses a thread pool like Dispatchers.IO or Dispatchers.Default does not guarantee that the block executes on the same thread from top to bottom. In some situations, Kotlin coroutines might move execution to another thread after a suspend-and-resume. This means thread-local variables might not point to the same value for the entire withContext() block.
but I didn't get this specific sentence
This means thread-local variables might not point to the same value for the entire withContext() block
Can anyone show me an example of this scenario?
myLooper()
and prepare()
on Looper
use a thread-local variable for holding a per-thread Looper
instance.
So, imagine this scenario:
launch()
a coroutine on Dispatchers.Default
prepare()
a Looper
and try using that for something (e.g., with a Messenger
)suspend
functionWhen that suspend
function returns, you may not be on the same thread as you were on before calling that suspend
function. It will be a thread from Dispatchers.Default
, but not necessarily the specific thread you were on before. As a result, your Looper
might be associated with some other thread, one that you're fighting with the coroutines system to use. Depending on what you were trying to do here, the fact that you are on a different thread might cause problems in what you wanted the Looper
for.
The real lesson here is: use HandlerThread
to get a Looper
, rather than prepare()
.
This refers to variables that are static to a thread (see this for reference).
Most likely this does not concern you, usage of thread local variables is rather specific. The fact that your coroutine may jump to a different thread when resumed will have no impact in normal cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With