3 ms·
I think coroutines is probably the best implementation of cooperative multitasking (async/await) that is is available in any language: They build on structured
by Matthias247 4y ago
I think coroutines is probably the best implementation of cooperative multitasking (async/await) that is is available in any language: They build on structured concurrency and thereby allow to prevent a few common concurrency problems like runaway tasks. You can run them on different threading systems, like UI threads, threadpools, etc. And they default to run the continuation on the correct thread.
However as any async/await implementation it will obviously still have challenges. The "colored" world of functions means users need to know the differences between suspend functions and other functions, and using something wrong can lead to performance issues.
One thing to note is that with the upcoming of virtual threads (Project Loom) in Java itself, the need for using coroutines might become much smaller. You might just end up using them for UI work, and everything else could use virtual threads. That could simplify a lot of things.
- jillesvangurp 4y agoLoom will just slot into co-routines without requiring many (if any) code changes. It's still going to be nicer to use co-routines from an API point of view and they'll just use the loom stuff underneath pretty much transparently when it is available. A virtual thread is basically just yet another thing that you can wrap with a co-routine. There are many such things across the jvm, js, and ios-native platforms that are supported via Kotlin already. And since it is API compatible with things that are already supported by co-routines, pretty much all you need to do is change your custom co-routine contexts to be backed by virtual threads rather than actual threads. This should just work even without explicit support for this in the co-routines library (it's just another thread pool). But they obviously will add explicit Loom support as well as it makes sense to make co-routines be virtual threads pretty much always. When that ships, all current kotlin code that uses co-routines will be using virtual thread on a Loom capable jvm. It already has structured concurrency and all the rest so all of that will continue to work. And some of the blocking Java stuff that you currently need thread backed co-routine contexts for, will stop being blocking so you can stop doing that. But it will still work of course.
- Matthias247 4y agoI guess you could "slot loom into co-routines", but the niceness of loom is that you don't even have to use coroutines. It could just be regular "blocking" Kotlin functions which run on virtual threads. If you already use Kotlin coroutines - fine to continue to use them. But I imagine for a new project you might want to opt to build on virtual threads instead of coroutines.