What is Korutina in Kotlin?

Original author: Amit Shekhar
  • Transfer

What is Korutina in Kotlin?


Korutiny is an excellent feature available in the Kotlin language. I have already tried it and I really liked it.


The purpose of this article is to help you understand Korutins. Just be careful when reading and you will succeed.


Let's start with the official definition of Korutin.


Korutiny is a new way of writing asynchronous, non-blocking code.

The first question that arises when reading this definition is - how do the Korutins differ from the streams?


Korutins are lightweight streams. A lightweight stream means that it is not tied to the native thread, so it does not require a context switch to the processor, so it is faster.


What does this mean, "not tied to the native stream" ?


Korutiny is in many programming languages.


Basically, there are two types of Korutin:


  • using a stack;
  • unused stack;

Kotlin implements Korutin without a stack - this means that Korutin does not have its own stack, so they are not tied to the native stream.


Both the Korutins and the threads are multitasking. But the difference is that threads are managed by the OS, and Korutins are users.


Now you can consciously read and understand an excerpt from the official Kotlin website:


Korutiny can be represented as a lightweight stream. Like threads, cortinos can work in parallel, wait for each other and communicate. The biggest difference is that corutines are very cheap, almost free: we can create them by the thousands and pay very little in terms of performance. Flows are expensive. A thousand threads can be a serious problem even for a modern car.

Let's see how to work with Korutins.


So, how to start korutina (by analogy with the launch of the stream)?


There are two functions to run cortina:


  • launch{}
  • async{}

launch {} vs async {} in Kortlin Korutinah


The difference is that launch{}it does not return anything, but async{}returns an instance Deferredin which there is a function await()that returns the result of the coroutine, just like Futurein Java, where we do future.get()to get the result.


Let's take a look at using launch {}


funmain(args: Array<String>) {
    println("Kotlin Start")
    launch(CommonPool) {
        delay(2000)
        println("Kotlin Inside")
    }
    println("Kotlin End")
}

// The output will be
// Kotlin Start
// Kotlin End
// Kotlin Inside

This code will launch a new cortina in this thread pool. In this case, we use CommonPool , which uses ForkJoinPool.commonPool () . Threads still exist in a corutin-based program, but a single thread can run many coroutines, so there is no need for too many threads.


Let's try one thing:


funmain(args: Array<String>) {
    delay(2000)
}

If you do this directly in the main function, you will receive an error message:


The interrupt functions can only be called from a corort or other interrupt function.


The delay function is an interrupt function, so we can only call it from cortina or another interrupt function.


Let's fix this:


funmain(args: Array<String>) {
    runBlocking {
        delay(2000)
    }
}

One more example:


suspendfundoWorkFor1Seconds(): String {
    delay(1000)
    return"doWorkFor1Seconds"
}

suspendfundoWorkFor2Seconds(): String {
    delay(2000)
    return"doWorkFor2Seconds"
}

// Serial execution privatefundoWorksInSeries() {
    launch(CommonPool) {
        val one = doWorkFor1Seconds()
        val two = doWorkFor2Seconds()
        println("Kotlin One : " + one)
        println("Kotlin Two : " + two)
    }
}

// The output is
// Kotlin One : doWorkFor1Seconds
// Kotlin Two : doWorkFor2Seconds

Now look at using async {}


// Parallel executionprivatefundoWorksInParallel() {
    val one = async(CommonPool) {
        doWorkFor1Seconds()
    }
    val two = async(CommonPool) {
        doWorkFor2Seconds()
    }
    launch(CommonPool) {
        val combined = one.await() + "_" + two.await()
        println("Kotlin Combined : " + combined)
    }
}
// The output is// Kotlin Combined : doWorkFor1Seconds_doWorkFor2Seconds

Since we use async{}, we can call await()to get the result.


Happy learning;)


Also popular now: