https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

maxmello

01/16/2019, 10:41 AM
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

zokipirlo

01/16/2019, 10:59 AM
For synchronized things I'm using
actor
and
sealed class
to define operations which I want to do.
m

maxmello

01/16/2019, 12:20 PM
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

zokipirlo

01/16/2019, 1:07 PM
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

Dico

01/16/2019, 4:22 PM
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

uli

01/16/2019, 8:24 PM
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

Dico

01/16/2019, 8:25 PM
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

uli

01/16/2019, 8:29 PM
You mean, the compile complains?
d

Dico

01/16/2019, 8:29 PM
yeah
u

uli

01/16/2019, 8:29 PM
That's a good thing®
d

Dico

01/16/2019, 8:29 PM

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

👍 1
2 Views