What happen with coroutines when main thread exits?

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 executor.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.


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.