Sep 18, 2020

What are Coroutines

I'm reading the Kotlin documentation, and the question arises. What are coroutines actually? The keyword suspend is used in the syntax and I think that's a clue. I believe Coroutines are blocks of code that can suspend the execution. Meaning that the thread working on the things in the thread could do some of the things in the coroutine, and then suspend the work to work on other things. How would this be working?

Well, I don't know, but I think that a clue is found by looking at Javascript and actors in Scala. The idea here is that code execution is happening by scheduling function calls onto a queue, and then there is an Event Loop that is tackling these function calls one by one. Javascript is, when just using basic Javascript, thread safe, because there is only one thread. It looks like this is more, but that is because the event loop simply just do it's work in small chunks. The same thing is happening in Scala with Akka, where you have an actor system who's execution also basically occurs through an event loop. This turned out to be a very powerful paradigm for code, since it allows web servers to handle loads of requests at the same time, because of this suspending of execution, a service can tend to many requests in parallel without having to have an expensive thread working for each request.

My belief is that this is the idea that Kotlin has now taken and integrated into the language. You could, as I said, already do this in Scala, because it's not really built into the language. You need to create an ActorSystem that can handle tasks etc.. In Kotlin you only seem to need to use the runBlocking or coroutineScope to write code that I believe gets scheduled into internal event loops. The advantage compared to for example Javascript is of course that Kotlin still easily can be working with many threads, making better use of multi core processors.