kotlinkotlin-coroutines

Is kotlin coroutine Job's status is reliable for concurrency control?


I've read this sentence in the Java Concurrency in Practice book that:

The result of Thread.getState should not be used for concurrency control, and is of limited usefulness for testing—its primary utility is as a source of debugging information.

I wonder is this a valid statement about Kotlin Coroutine Job's status?

For example should we avoid checking isActive as follow (from Kotlin documentation):

val watchdogDispatcher = Dispatchers.IO.limitParallelism(1)
fun backgroundWork() {
    println("Doing bookkeeping in the background in a non-suspending manner")
    Thread.sleep(100L) // Sleep 100ms
}
// Part of some non-trivial CoroutineScope-confined lifecycle
launch(watchdogDispatcher) {
    while (isActive) {
        // Repetitively do some background work that is non-suspending
        backgroundWork()
    }
}

Solution

  • Checking on isActive is fine in Kotlin, as the example code from the official documentation shows - no reason to doubt that.

    Another option is to use ensureActive(), which internally tests for isActive and (if false) aborts the current coroutine right then and there by throwing a CancellationException. That is the mechanism how coroutines in Kotlin communicate their status to other nodes in the coroutine hierarchy. The documentation provides this example:

    while (true) {
        // Repeatatively do some background work that is non-suspending
        backgroundWork()
        ensureActive() // Bail out if the scope was cancelled
        postBackgroundCleanup() // Won't be invoked if the scope was cancelled
    }