Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Coroutines - Thread Switching

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?

like image 462
theapache64 Avatar asked Apr 07 '20 16:04

theapache64


2 Answers

myLooper() and prepare() on Looper use a thread-local variable for holding a per-thread Looper instance.

So, imagine this scenario:

  • You launch() a coroutine on Dispatchers.Default
  • In that coroutine, you prepare() a Looper and try using that for something (e.g., with a Messenger)
  • You then call some suspend function

When 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().

like image 183
CommonsWare Avatar answered Oct 21 '22 17:10

CommonsWare


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.

like image 2
Francesc Avatar answered Oct 21 '22 17:10

Francesc