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

apomelov

09/28/2018, 6:10 PM
Hi. I'm trying to understand coroutines a bit deeply, but missing some materials for the very beginning. I heard that coroutines are much "cheaper" than threads. Sounds nice. Does it mean that I shouldn't use threads anymore? Each time I want to run some parallel computation I use coroutines instead of threads now?
l

louiscad

09/28/2018, 6:34 PM
Your coroutines still run on threads, but your threads are reused more often, and rarely blocked just for the sake of waiting sequentially. That allows you to have much less threads (they do take their share of RAM, so having too much of them is not so good). There's two talks by Roman Elizarov at last year's KotlinConf, and official docs of kotlinx.coroutines library to learn it properly 🙂
a

apomelov

09/28/2018, 6:57 PM
So for example I need to make lots of IO calls and small processing afterwards. With naive implementation with threads I'll have lots of threads mainly waiting for the IO. And with coroutines there will be a few threads continuously processing data. Did I catch the idea?
And probably non-blocking IO will be used, so we don't need actual threads waiting for the response.
l

louiscad

09/28/2018, 7:01 PM
You caught a part of it, yeah. What coroutines really allow is avoiding callback hells, by allowing methods that write sequentially, yet, can free the thread, wait for one or more "callbacks" or other suspend calls, then resume on the initial thread, and kotlinx.coroutines provides top notch cancellation support, and structured concurrency now.
yes, if you use non-blocking I/O, this can integrate well with coroutines, and reduce the need for many threads a lot more. Since version 0.26.1, kotlinx.coroutines provides
<http://Dispatcher.IO|Dispatcher.IO>
that has good defaults for when you need to do blocking I/O.
a

apomelov

09/28/2018, 7:03 PM
Ok, thanks a lot, now I can take the kotlinconf materials.
It was the first brick of my coroutines understanding:)
👍 2
3 Views