Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't exit Kotlin program while several coroutines are running

At several points of my program, I use launch to start a coroutine that does some background tasks. Then, at some point, I return from the main function. A simplified version of my program could look like this:

fun main(args : Array<String>)
{
    launch {
        delay(10000) // some long running operation
        println("finished")
    }
}

Now, the coroutine starts as expected and starts running the operation - and then the program exits. If I don't return from main or replace launch with thread, everything works as expected. So how can I, given that I don't keep track of all coroutines started in my program (hence I cannot use .join() or .await()), make sure that all coroutines finish before my program exits?

like image 428
msrd0 Avatar asked Sep 20 '25 19:09

msrd0


1 Answers

So how can I, given that I don't keep track of all coroutines started in my program (hence I cannot use .join() or .await()), make sure that all coroutines finish before my program exits?

You need to keep track and await the results at some point in order to be sure that those coroutines have finished. That’s because “coroutines are like daemon threads”:

Active coroutines do not keep the process alive. They are like daemon threads.

This is not the case for regular Java Threads which are non-daemon by default.

like image 58
s1m0nw1 Avatar answered Sep 22 '25 22:09

s1m0nw1