While migrating old code to coroutines I always en...
# coroutines
m
While migrating old code to coroutines I always encounter blocking code, like IO, synchronized blocks, wait / notify etc. Not everything can be changed to be suspending rather than blocking, so what is the worst case scenario with blocking code inside coroutines? Should I just always use the IO Dispatcher to make sure enough threads are available, or can blocking code inside coroutines have negative consequences to the point where I should explicitly not use them and stick to Thread? So for example, is
GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { synchronized(lock) { // some operations } }
potentially worse than
thread { synchronized(lock) { // some operations } }
?
z
For synchronized things I'm using
actor
and
sealed class
to define operations which I want to do.
m
There is also Mutex which can be used for this, right? But that wasn’t my question, synchronized is just some example, it could also be Thread.sleep(). I still struggle with understanding if I can somehow “brick” the coroutine system by blocking threads too often that are used for coroutines
z
I'm using example like
launch { while (isActive) { doSomething(); delay(1000)}}
. Simple implementation of
ticker
. It works without a problem. Nothing is blocked. When you cancel coroutineContext, coroutine (while) is also stopped. Much better than Rx intervals 🙂
d
Many things can be replaced with non blocking calls. Some things cannot, yet, and a good approach would be to wrap those in
withContext (IO) {}
block.
👍 1
u
I guess, if you suspend inside a synchronized block you might get in real trouble. I am not exactly sure what will happen. Either the generated byte code will release the monitor during suspend and re aquire it at continuation or worse, only release the monitor at the end of the block as expected, which might be on a different thread.
d
sounds scary. So basically don't suspend inside a synchronized block.
There's an inspection against it
you can't have suspension points in synchronized blocks
u
You mean, the compile complains?
d
yeah
u
That's a good thing®
d

https://i.imgur.com/QAxW9U7.png

👍 1