Skip to content
Advertisement

Kotlin process waits for all threads to finish?

I wrote this simple testing program:

fun main() {
    println("Main Start")

    thread {
        println("Thread Start")
        Thread.sleep(3000)
        println("Thread End")
    }

    println("Main End")
}

As I can see, the output is:

Main Start
Main End
Thread Start
Thread End

My expectation is that at-least the “Thread End” message will not be printed, Cause that main function is ended and this main thread should be done running.

Is Kotlin process always waiting for threads to finish before done?

Advertisement

Answer

The thread that you have created is a non-daemon thread, and just like in Java, the JVM will not terminate until all the non-daemon thread are finished.

From Kotlin documentation one can read:

fun thread(
    start: Boolean = true, 
    isDaemon: Boolean = false, 
    contextClassLoader: ClassLoader? = null, 
    name: String? = null, 
    priority: Int = -1, 
    block: () -> Unit ): Thread Creates a thread that runs the specified block of code.

Parameters

start – if true, the thread is immediately started.

isDaemon – if true, the thread is created as a daemon thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

contextClassLoader – the class loader to use for loading classes and resources in this thread.

name – the name of the thread.

priority – the priority of the thread.

Threads in Kotlin, by default, are non-daemon threads. This is why you can still see the output of the thread even thought the main thread have finished its execution. Set the isDaemon to true, and you will see the following output instead:

Main Start
Main End
Thread Start
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement