Cancellation and timeouts

suggest change

Long-running work has to be stoppable: the user leaves a screen, an HTTP request is aborted, a server shuts down, or an operation simply takes too long. In Kotlin this is handled by Coroutines from kotlinx.coroutines, which have built-in, structured support for cancellation and timeouts.

This article covers:

All examples use this dependency:

// build.gradle.kts
dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
}

Cancelling a coroutine

launch returns a Job. Calling cancel() on it requests cancellation, and join() waits until the coroutine has actually finished. cancelAndJoin() does both:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        repeat(1000) { i ->
            println("job: I'm sleeping $i ...")
            delay(500L)
        }
    }
    delay(1300L)
    println("main: I'm tired of waiting!")
    job.cancelAndJoin()
    println("main: Now I can quit.")
}
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
main: Now I can quit.

The coroutine was suspended in delay when it was cancelled. delay noticed the cancellation and threw CancellationException, which unwound the coroutine. A CancellationException is treated as normal completion of a cancelled coroutine: it is not printed and doesn't crash the program.

For async, cancel the Deferred the same way. Calling await() on a cancelled Deferred throws CancellationException.

Job states

A cancelled job first goes to the cancelling state (it runs its finally blocks and waits for its children) and only then to cancelled. You can observe this with isActive, isCancelled and isCompleted:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch { delay(10_000) }
    delay(100)

    fun state() = "active=${job.isActive} cancelled=${job.isCancelled} completed=${job.isCompleted}"

    println("running:    ${state()}")
    job.cancel()
    println("cancelling: ${state()}")
    job.join()
    println("cancelled:  ${state()}")
}
running:    active=true cancelled=false completed=false
cancelling: active=false cancelled=true completed=false
cancelled:  active=false cancelled=true completed=true

That's why you usually want cancelAndJoin() rather than just cancel(): after cancel() returns, the coroutine may still be running its cleanup code.

Cancelling with a reason

cancel accepts a message or a CancellationException, which is useful for logging why something was stopped:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            delay(10_000)
        } catch (e: CancellationException) {
            println("cancelled: ${e.message}")
            throw e // always rethrow
        }
    }
    delay(100)
    job.cancel("user navigated away")
    job.join()
}
cancelled: user navigated away

Cancellation is cooperative

Cancellation doesn't kill a thread. It sets a flag on the Job, and the coroutine has to check that flag. All suspending functions in kotlinx.coroutines (delay, yield, withContext, await, join, channel operations, ...) check it and throw CancellationException. Code that never suspends never notices:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val startTime = System.currentTimeMillis()
    val job = launch(Dispatchers.Default) {
        var nextPrintTime = startTime
        var i = 0
        while (i < 5) { // busy loop that never suspends
            if (System.currentTimeMillis() >= nextPrintTime) {
                println("job: I'm sleeping ${i++} ...")
                nextPrintTime += 500L
            }
        }
    }
    delay(1300L)
    println("main: I'm tired of waiting!")
    job.cancelAndJoin()
    println("main: Now I can quit.")
}
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: I'm sleeping 3 ...
job: I'm sleeping 4 ...
main: Now I can quit.

The loop ran to completion despite being cancelled, and cancelAndJoin() had to wait for it. There are three ways to fix it:

Approach Behavior
while (isActive) checks the flag; you decide how to exit
ensureActive() throws CancellationException if the job is cancelled
yield() checks cancellation and also lets other coroutines on the same dispatcher run
import kotlinx.coroutines.*

fun main() = runBlocking {
    val startTime = System.currentTimeMillis()
    val job = launch(Dispatchers.Default) {
        var nextPrintTime = startTime
        var i = 0
        while (isActive) { // property of CoroutineScope
            if (System.currentTimeMillis() >= nextPrintTime) {
                println("job: I'm sleeping ${i++} ...")
                nextPrintTime += 500L
            }
        }
        println("job: exiting loop cleanly")
    }
    delay(1300L)
    println("main: I'm tired of waiting!")
    job.cancelAndJoin()
    println("main: Now I can quit.")
}
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: exiting loop cleanly
main: Now I can quit.

In a regular suspending function that isn't an extension of CoroutineScope, use currentCoroutineContext().ensureActive() or coroutineContext.isActive. For example, when processing a big list:

suspend fun processAll(items: List<String>) {
    for (item in items) {
        currentCoroutineContext().ensureActive()
        heavyComputation(item)
    }
}

Don't swallow CancellationException

Because cancellation is delivered as an exception, a catch-all catch (e: Exception) (or runCatching) also catches it. The coroutine then keeps running as if nothing happened:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        repeat(5) { i ->
            try {
                println("job: $i")
                delay(500)
            } catch (e: Exception) {
                println("job: caught ${e.javaClass.simpleName}")
            }
        }
    }
    delay(1300)
    println("main: cancelling")
    job.cancelAndJoin()
    println("main: done")
}
job: 0
job: 1
job: 2
main: cancelling
job: caught JobCancellationException
job: 3
job: caught JobCancellationException
job: 4
job: caught JobCancellationException
main: done

The job is still cancelled, so every later delay throws immediately. But any non-suspending work in the loop (here println, in real code maybe a database write) keeps running. Rethrow CancellationException before handling other errors:

try {
    doWork()
} catch (e: CancellationException) {
    throw e
} catch (e: Exception) {
    log.error("doWork failed", e)
}

If you must use a catch-all, call currentCoroutineContext().ensureActive() at the start of the handler. It rethrows if the coroutine was cancelled and does nothing otherwise.

Cleanup with finally

Since cancellation unwinds the coroutine with an exception, try/finally and use work as expected (see use and Closeable):

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(1000) { i ->
                println("job: working $i")
                delay(500L)
            }
        } finally {
            println("job: releasing resources")
        }
    }
    delay(1300L)
    job.cancelAndJoin()
    println("main: done")
}
job: working 0
job: working 1
job: working 2
job: releasing resources
main: done

There is a catch: inside finally the coroutine is already cancelled, so calling a suspending function there (e.g. flushing to a socket, or closing a connection with a suspending close) throws CancellationException straight away. Wrap suspending cleanup in withContext(NonCancellable):

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(1000) { i ->
                println("job: working $i")
                delay(500L)
            }
        } finally {
            withContext(NonCancellable) {
                println("job: saving state...")
                delay(200L) // would throw without NonCancellable
                println("job: state saved")
            }
        }
    }
    delay(1300L)
    job.cancelAndJoin()
    println("main: done")
}
job: working 0
job: working 1
job: working 2
job: saving state...
job: state saved
main: done

Use NonCancellable only for short cleanup code with withContext. Never pass it to launch or async: that breaks the parent-child relationship and the coroutine can no longer be cancelled by its parent.

withTimeout

Most of the time you don't cancel a job manually but give an operation a deadline. withTimeout runs a block and cancels it if it doesn't finish in time, throwing TimeoutCancellationException:

import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        withTimeout(1300L) {
            repeat(1000) { i ->
                println("I'm sleeping $i ...")
                delay(500L)
            }
        }
    } catch (e: TimeoutCancellationException) {
        println("Timed out: ${e.message}")
    }
}
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
Timed out: Timed out waiting for 1300 ms

There's also an overload taking kotlin.time.Duration, which reads better:

import kotlin.time.Duration.Companion.seconds

val user = withTimeout(5.seconds) { api.loadUser(id) }

TimeoutCancellationException is a subclass of CancellationException. That has an important consequence: if you don't catch it inside a launched coroutine, the coroutine just ends silently, like any cancelled coroutine. The timeout is not reported to a CoroutineExceptionHandler and nothing is logged. Catch it where the timeout is meaningful, or use withTimeoutOrNull.

As with manual cancellation, the timeout only takes effect at a suspension point. A block of blocking or CPU-bound code inside withTimeout keeps running past the deadline.

withTimeoutOrNull

withTimeoutOrNull returns null on timeout instead of throwing, which is usually more convenient:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val result = withTimeoutOrNull(1300L) {
        repeat(1000) { i ->
            println("I'm sleeping $i ...")
            delay(500L)
        }
        "Done" // will be cancelled before it produces this result
    }
    println("Result is $result")

    val fast = withTimeoutOrNull(1300L) {
        delay(100L)
        "Done"
    }
    println("Result is $fast")
}
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
Result is null
Result is Done

If the block itself can legitimately return null, you can't tell that apart from a timeout. Return a wrapper (e.g. Result or a sealed class) or use withTimeout in that case.

A common pattern is a fallback value:

val config = withTimeoutOrNull(2.seconds) { remoteConfig.fetch() } ?: Config.DEFAULT

Timeouts for parallel work

A timeout around several async calls applies to all of them together. When it expires, every unfinished child is cancelled:

import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.seconds

suspend fun fetch(name: String, ms: Long): String {
    delay(ms)
    return "$name done"
}

fun main() = runBlocking {
    val all = withTimeoutOrNull(1.seconds) {
        listOf(
            async { fetch("a", 300) },
            async { fetch("b", 2000) },
        ).awaitAll()
    }
    println("all: $all")

    // per-task timeouts: slow tasks are replaced, fast results are kept
    val each = listOf("a" to 300L, "b" to 2000L, "c" to 600L).map { (name, ms) ->
        async { withTimeoutOrNull(1.seconds) { fetch(name, ms) } ?: "$name timed out" }
    }.awaitAll()
    println("each: $each")
}
all: null
each: [a done, b timed out, c done]

Cancellation propagates through the hierarchy

Coroutines form a tree. This is called structured concurrency and it gives three rules:

  1. Cancelling a parent cancels all its children.
  2. A parent doesn't complete until all its children have completed.
  3. If a child fails with an exception (other than CancellationException), the parent is cancelled, and with it all the other children.

Rule 1:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val parent = launch {
        launch {
            try { delay(Long.MAX_VALUE) } finally { println("child 1 cancelled") }
        }
        launch {
            try { delay(Long.MAX_VALUE) } finally { println("child 2 cancelled") }
        }
    }
    delay(100)
    parent.cancelAndJoin()
    println("parent cancelled: ${parent.isCancelled}")
}
child 1 cancelled
child 2 cancelled
parent cancelled: true

Rule 3, using coroutineScope, which is how you should run parallel work inside a suspending function:

import kotlinx.coroutines.*

fun main() = runBlocking<Unit> {
    try {
        coroutineScope {
            launch {
                try {
                    delay(1000)
                    println("slow task done")
                } catch (e: CancellationException) {
                    println("slow task cancelled")
                    throw e
                }
            }
            launch {
                delay(100)
                throw IllegalStateException("fast task failed")
            }
        }
    } catch (e: IllegalStateException) {
        println("caught: ${e.message}")
    }
}
slow task cancelled
caught: fast task failed

If you want siblings to be independent, so that one failing doesn't cancel the others, use supervisorScope (or a SupervisorJob for a long-lived scope). Cancelling the supervisor itself still cancels all its children.

On Android, viewModelScope and lifecycleScope use this mechanism: when the ViewModel is cleared or the lifecycle is destroyed, the scope is cancelled and every coroutine started in it is cancelled too. On a server, cancel your application-wide CoroutineScope on shutdown for the same effect.

Making blocking code cancellable

Blocking calls like Thread.sleep, InputStream.read or JDBC queries don't check the coroutine's cancellation flag. runInterruptible runs a blocking block and interrupts its thread when the coroutine is cancelled, turning the resulting InterruptedException into CancellationException:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            runInterruptible(Dispatchers.IO) {
                Thread.sleep(10_000) // blocking call
                println("never printed")
            }
        } catch (e: CancellationException) {
            println("blocking call interrupted")
            throw e
        }
    }
    delay(200)
    job.cancelAndJoin()
    println("main: done")
}
blocking call interrupted
main: done

This only helps for code that responds to thread interruption. Some blocking I/O (e.g. classic java.net.Socket reads) ignores interrupts; for those, close the underlying resource from an invokeOnCompletion handler or set a socket/driver-level timeout instead. For example, the JDBC from Kotlin driver can be given Statement.setQueryTimeout, and HTTP client libraries have their own connect and request timeouts.

Making callback APIs cancellable

When wrapping a callback-based API in a suspending function, use suspendCancellableCoroutine (not suspendCoroutine) and register an invokeOnCancellation handler that stops the underlying operation:

import kotlinx.coroutines.*
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume

val scheduler = Executors.newSingleThreadScheduledExecutor()

// pretend this is a callback-based network call
suspend fun fetchLater(value: String, ms: Long): String =
    suspendCancellableCoroutine { cont ->
        val future = scheduler.schedule({ cont.resume(value) }, ms, TimeUnit.MILLISECONDS)
        cont.invokeOnCancellation {
            future.cancel(false)
            println("underlying operation cancelled")
        }
    }

fun main() = runBlocking {
    println("fast: " + withTimeoutOrNull(500) { fetchLater("hello", 100) })
    println("slow: " + withTimeoutOrNull(500) { fetchLater("hello", 2000) })
    scheduler.shutdown()
}
fast: hello
underlying operation cancelled
slow: null

suspendCancellableCoroutine makes the caller resume with CancellationException as soon as it is cancelled, even if the callback never fires. invokeOnCancellation lets you release what the operation holds. The handler may run on any thread, so keep it short and thread-safe.

Timeouts and resources

The timeout can fire right after the block has acquired a resource but before the result is returned to you. The result is then lost, and so is the resource:

val conn = withTimeout(1.seconds) { pool.acquire() } // may leak if timeout races with return

Store the resource in a variable outside the timeout and release it in finally:

var conn: Connection? = null
try {
    withTimeout(1.seconds) {
        conn = pool.acquire()
    }
    query(conn!!) // work with the connection
} finally {
    conn?.close()
}

Gotchas

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents