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?