Coroutine in Kotlin


Coroutine in Kotlin

A coroutine is an example of suspendable computing. It's conceptually similar to a thread, meaning we need to run a block code that works simultaneously with the rest of the code. However, a Coroutine is not attached to any particular thread, and it may suspend its execution on one thread and resume on another. Coroutines can be considered lightweight threads, but there are several significant differences that make their actual life use very different from threads.

Coroutine Structural Concurrency

Coroutines follow a principle of structural concordance, which means that new coroutines can only be launched within a specific course scope that limits the life of the Coroutine.

In an actual life application, you will launch a lot of carotenes. Structural concurrence ensures that they are not lost or leaked. An outer scope cannot complete all of its child coroutines until they are complete. Structured concurrence ensures that any errors in the code are appropriately reported and never lost.

The Coroutine Scope Builder

The makers of run-blocking and coroutineScope may look alike because they are waiting for their bodies and their children to finish. The main difference is that the run-blocking method prevents the current thread from staying, while the Coroutine scope pauses and releases the base thread for other uses. Because of that difference, run-blocking is a regular function, and coroutine scope is a suspension function.

The Scope Builder and Concurrency - A coroutineScope builder can perform multiple concurrent operations on any suspension function.

Coroutine - An Explicit Job

A launch Coroutine builder returns a job object on a handle for the launched Coroutine, which can be used to wait until it is completed.

Coroutine as lightweight

Coroutines are less resource-intensive than JVM threads. When using threads, the code that erases the available memory of the JVM can be expressed using coroutines without reaching the resource limit. For example, the following code launches 100000 different coroutines, each waiting 5 seconds and printing a period ('.') with very little memory.