Son Truong
Son Truong

Reputation: 14183

What happen with coroutines when main thread exits?

In Java when main thread exits, all user threads (non-deamon threads) will keep running until they finish their job.

I have a simple program which print a counter from 1 to 5 to console.

Java version:

fun main(args: Array<String>) {
    println("Main start")

    countWithThread()

    println("Main end")
}

fun countWithThread() {
    Thread(Runnable {
        for (i in 1..5) {
            println("${Thread.currentThread().name} count $i")
            Thread.sleep(10)
        }
    }).start()
}

Output:

Main start
Main end
Thread-0 count 1
Thread-0 count 2
Thread-0 count 3
Thread-0 count 4
Thread-0 count 5

Process finished with exit code 0

Kotlin version:

fun main(args: Array<String>) {
    println("Main start")

    countWithCoroutine()

    println("Main end")
}

fun countWithCoroutine() {
    launch(CommonPool) {
        for (i in 1..5) {
            println("${Thread.currentThread().name} count $i")
            delay(10)
        }
    }
}

Output:

Main start
Main end

Process finished with exit code 0

As you can see, when main thread exits, the code in the coroutine does not run anymore. It seems Kotlin terminate all coroutines under the hood.

Can anyone tell me what exactly happen with coroutines when main thread exits?

Upvotes: 9

Views: 3915

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200168

Coroutines on their own aren't "running" in a way that the JVM would know about. They're nothing but objects on the heap.

However, the coroutine context does have a say in when it will allow the JVM to terminate. Create your own:

val threadPool = Executors.newFixedThreadPool(4)
val dispatcher = threadPool.asCoroutineDispatcher()

Now if you use it instead of CommonPool:

launch(dispatcher) { ... }

you'll find the JVM doesn't die at all, even when all the tasks are done. It will exit only when you explicitly say

threadPool.shutdown()

Note, however, that threadPool.shutdown() doesn't behave towards coroutines the same as towards the "classic" tasks you submit to it. The executor will ensure all the submitted tasks are done before shutting down, but it has no account of the suspended coroutines.

Upvotes: 8

zsmb13
zsmb13

Reputation: 89578

Coroutines are terminated when the main thread finishes execution and the process/JVM instance dies, they are like daemon threads. See this section in the official coroutine guide for reference.

Upvotes: 5

Related Questions