Shutdown hook with coroutine

How can we add a shutdown hook from main for coroutines?

fun poll() = arrayOf(1,2,3,4,5,6,7,8,9)

val job = scope.launch {
    while (isActive) {
        val records = poll()
        records.forEach {
            Thread.sleep(500)
            print("$it, ")
        }
        println("job completed")
    }
}

GlobalScope.launch {
    Runtime.getRuntime().addShutdownHook(object : Thread() {
        override fun run() {
            println("Gracefully shutting down")
            job.cancelAndJoin() // cannot call this here
            println("Gracefully shut!!!")
            delay(20000)
        }
    })
}

cancelAndJoin cannot be called in a shutdown hook because it’s a suspending function. What I’m trying to do is: when shutting down, cancel the job and wait for it to complete before terminating the JVM. How can we do that with coroutines?

1 Like

Do not use Thread.sleep you are not working with treads, but with coroutines, which are fibers. Use delay().

Also:

Runtime.getRuntime().addShutdownHook(object : Thread() {
        override fun run() = runBlocking {
            println("Gracefully shutting down")
            job.cancelAndJoin() // cannot call this here
            println("Gracefully shut!!!")
            delay(20000)
        }
    })

The problems you are facing are the basics about coroutines. I really recommend you to read the documentation.

3 Likes