DEV Community

Cover image for Cancelled, but Still Running: How Cooperative Cancellation Quietly Drains Your Users’ Battery
Android Expert
Android Expert

Posted on Originally published at Medium

Cancelled, but Still Running: How Cooperative Cancellation Quietly Drains Your Users’ Battery

Coroutines don’t stop by magic. CPU-bound loops, blocking I/O and swallowed CancellationExceptions keep working long after the screen is gone, and your users pay for it in battery and heat.

Every Android team I have worked with eventually ships the same bug. A user opens a screen, a coroutine starts, the user leaves, viewModelScope is cancelled, and the profiler shows the CPU pinned anyway. Nothing crashed. No stack trace exists. The code did exactly what it was told.

The root cause is a single design decision in kotlinx.coroutines: cancellation is cooperative. This post walks through what that means, the three failure modes that follow from it, and the Kotlin patterns that fix them.

1. What “cooperative” means

Calling job.cancel() does not interrupt a thread, kill a stack frame or unwind anything. It flips the job's state to Cancelling and returns. That's the entire request.

Whether the coroutine actually stops depends on whether it later reaches a suspension point that checks the job state. Functions such as delay, withContext, Channel.send and Flow.collect are all cancellable: on resumption (or on entry), they notice the job is no longer active and throw CancellationException. That exception unwinds the coroutine through its finally blocks, and the job completes as Cancelled.

If no such checkpoint is ever reached, nothing happens. The coroutine is “cancelled” in the bookkeeping sense and fully alive in the CPU sense.

cancel-is-a-request

Two consequences to keep in mind for the rest of the post:

  1. Cancellation is only as prompt as your longest stretch of code between checkpoints.
  2. Cancellation travels as an exception. Anything that intercepts exceptions can intercept cancellation.

2. Demo: a tight loop that ignores cancel

Throughout this post, snippets that use 30.seconds-style durations assume import kotlin.time.Duration.Companion.seconds (Kotlin 1.6+).

Here is a deliberately plain example, runnable on the JVM with nothing but kotlinx-coroutines-core:

import kotlinx.coroutines.*

private fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    var d = 2
    while (d.toLong() * d <= n) {
        if (n % d == 0) return false
        d++
    }
    return true
}

fun main() = runBlocking {
    val started = System.nanoTime()

    val job = launch(Dispatchers.Default) {
        var found = 0
        var n = 2
        while (n < 8_000_000) {          // no suspension point anywhere in here
            if (isPrime(n)) found++
            n++
        }
        println("Finished anyway: $found primes")
    }

    delay(100)
    println("Cancelling after ~100 ms")
    job.cancelAndJoin()
    val elapsedMs = (System.nanoTime() - started) / 1_000_000
    println("cancelAndJoin() returned after $elapsedMs ms")
}
Enter fullscreen mode Exit fullscreen mode

You will see the “Finished anyway” line print before cancelAndJoin() returns, and the elapsed time will be seconds rather than ~100 ms. The loop has no suspension point, so nothing ever reads the cancelled state.

On a server, that is a latency problem. On a phone it is worse: the work was produced for a UI that no longer exists, and every wasted cycle is battery you can’t give back.

A realistic Android version of the same bug looks like this:

class ContactSheetViewModel(
    private val decoder: BitmapDecoder,
    private val filters: FilterPipeline,
) : ViewModel() {

    fun render(paths: List<String>) {
        viewModelScope.launch(Dispatchers.Default) {
            for (path in paths) {
                val bitmap = decoder.decode(path)   // plain blocking function
                filters.apply(bitmap)               // ~300 ms of pure CPU each
                _tiles.update { it + bitmap }
            }
        }
    }
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Note that the ViewModel survives a rotation, and so does its viewModelScope. That cuts both ways. If render() is called from onCreate (or from a LaunchedEffect whose key changes), every call starts another pipeline in the same long-lived scope, and the earlier ones keep running. And when the user finally leaves the screen, onCleared() cancels the scope, but a loop with no checkpoint never notices. Either way, you end up with CPU-heavy pipelines feeding state nobody is watching.

3. isActive, ensureActive() and yield()

Kotlin gives you three ways to add checkpoints to code that would otherwise never suspend. They look similar but have different consequences.

isactive-ensureactive-yield

isActive: check and decide

launch(Dispatchers.Default) {
    var n = 2
    while (isActive && n < LIMIT) {
        if (isPrime(n)) found++
        n++
    }
    publish(found)   // <-- still runs after cancellation, with partial data
}
Enter fullscreen mode Exit fullscreen mode

isActive is a property, so it never throws. That is convenient but dangerous: when the loop exits early, execution falls through to whatever comes next and the coroutine finishes normally, holding a half-computed result. If publish writes to a database or UI state, you've just committed garbage.

ensureActive(): check and unwind

launch(Dispatchers.Default) {
    var n = 2
    while (n < LIMIT) {
        if (n % 4_096 == 0) ensureActive()   // cheap, but no need to pay it every iteration
        if (isPrime(n)) found++
        n++
    }
    publish(found)   // only reached if the loop completed
}
Enter fullscreen mode Exit fullscreen mode

ensureActive() throws CancellationException if the job is cancelled, so code after the loop is skipped automatically and finally blocks run. For most CPU-bound loops this is the right default.

Inside a plain suspend fun that has no CoroutineScope receiver, use the context directly:

suspend fun checksum(chunks: Sequence<ByteArray>): Long {
    var acc = 0L
    for (chunk in chunks) {
        currentCoroutineContext().ensureActive()
        acc = acc xor crc(chunk)
    }
    return acc
}
Enter fullscreen mode Exit fullscreen mode

yield(): check and be polite

yield() is a real suspension point. It checks for cancellation first and throws immediately if the job is cancelled. Otherwise it gives other coroutines on the same dispatcher a chance to run before resuming you.

suspend fun reindexAll(documents: List<Document>) {
    for (doc in documents) {
        index(doc)   // blocking, CPU-bound
        yield()      // cancellable + lets sibling coroutines on this dispatcher breathe
    }
}
Enter fullscreen mode Exit fullscreen mode

Use it when fairness matters, for example on a limited parallelism dispatcher shared with other work. Avoid it in the hottest inner loop: re-dispatching has a cost that ensureActive() doesn't.

Blocking I/O is the same problem in disguise

A blocking InputStream.read() on Dispatchers.IO never reaches a checkpoint either. Two techniques help:

// 1. Convert cancellation into a thread interrupt for interruptible blocking calls.
suspend fun readLine(queue: BlockingQueue<String>): String =
    runInterruptible(Dispatchers.IO) { queue.take() }   // take() responds to interrupt
Enter fullscreen mode Exit fullscreen mode
// 2. For callback-style APIs, wire cancellation to the library's own cancel().
suspend fun Call.awaitResponse(): Response =
    suspendCancellableCoroutine { cont ->
        cont.invokeOnCancellation { cancel() }             // OkHttp's Call.cancel()
        enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                if (!cont.isCancelled) cont.resumeWithException(e)
            }
            override fun onResponse(call: Call, response: Response) {
                if (cont.isCancelled) response.close() else cont.resume(response)
            }
        })
    }
Enter fullscreen mode Exit fullscreen mode

runInterruptible only helps when the blocking call honors thread interrupts (Thread.sleep, BlockingQueue, NIO channels). Classic socket reads often don't, which is why the second pattern, cancelling at the library level, is usually the more reliable one. (Retrofit and Ktor already do this for you; the point is to know why when you wrap something else.)

4. The catch (e: Exception) anti-pattern

Because cancellation is delivered as an exception, any handler broad enough to catch it can stop it.

Here is a sync loop in the style I see in code review every month:

import kotlin.time.Duration.Companion.seconds

class SyncWorker(
    private val api: PendingApi,
    private val db: PendingDao,
    private val log: Logger,
) {
    suspend fun runForever() {
        while (true) {
            try {
                val batch = api.fetchPending()
                db.insertAll(batch)
                delay(30.seconds)
            } catch (e: Exception) {
                log.w("sync failed", e)      // "we'll just try again"
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

What happens when the owning scope is cancelled while delay is suspended?

  1. delay throws CancellationException.
  2. catch (e: Exception) catches it and logs a "failure".
  3. The loop goes round again. api.fetchPending() is a suspend call on an already-cancelled job, so it throws CancellationException immediately.
  4. The same catch swallows it. There is no delay to slow things down, because the exception was thrown before reaching it.

The result is a hot loop that logs thousands of lines a second, saturates a core, and never terminates. Nothing in the UI shows it.

swallowed-cancellation

The fix

Handle cancellation first and rethrow it:

import kotlin.coroutines.cancellation.CancellationException

suspend fun runForever() {
    while (true) {
        try {
            val batch = api.fetchPending()
            db.insertAll(batch)
            delay(30.seconds)
        } catch (e: CancellationException) {
            throw e                                  // never swallow this
        } catch (e: Exception) {
            log.w("sync failed", e)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Or, better, make the loop’s own condition cooperative so it can’t outlive its job even if somebody edits the catch later:

while (currentCoroutineContext().isActive) { /* ... */ }
Enter fullscreen mode Exit fullscreen mode

runCatching has the same flaw

val result = runCatching { api.fetchProfile() }   // also catches CancellationException
Enter fullscreen mode Exit fullscreen mode

runCatching catches Throwable, so it eats cancellation too. A small wrapper keeps the ergonomics and fixes the behavior:

inline fun <T> runCatchingCooperatively(block: () -> T): Result<T> =
    try {
        Result.success(block())
    } catch (e: CancellationException) {
        throw e
    } catch (e: Throwable) {
        Result.failure(e)
    }
Enter fullscreen mode Exit fullscreen mode

Some teams go further and ban runCatching in suspending code via a custom lint or Detekt rule. It's a defensible policy.

5. withContext(NonCancellable) for cleanup, and when not to use it

Once a job is cancelled, every suspending call in that coroutine throws immediately, including the ones inside your finally block. That is usually what you want, until cleanup itself needs to suspend.

class DraftUploader(
    private val draftStore: DraftStore,
    private val api: DraftApi,
) {
    suspend fun upload(draft: Draft) {
        val staged = draftStore.stage(draft)          // suspend: writes a temp record
        try {
            api.upload(staged)
        } finally {
            // If we were cancelled, a plain suspend call here would throw
            // and the staged record would leak. NonCancellable lets it finish.
            withContext(NonCancellable) {
                draftStore.discard(staged)
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

NonCancellable is a special Job that is always active. Inside withContext(NonCancellable), suspension points stop reacting to the outer cancellation, so short cleanup steps run to completion.

noncancellable-decision

Keep it small and bounded

The block can no longer be cancelled, so a slow call inside it holds the coroutine (and anything awaiting it) hostage. Pair it with a timeout:

finally {
    withContext(NonCancellable) {                  // needs kotlin.time.Duration.Companion.seconds
        withTimeoutOrNull(2.seconds) {
            draftStore.discard(staged)
        } ?: log.w("cleanup timed out for ${staged.id}")
    }
}
Enter fullscreen mode Exit fullscreen mode

If cleanup must be reliable and may take long (uploading a final analytics batch, for example), a coroutine is the wrong tool. Hand it to WorkManager.

What not to do

// ❌ Detaches the child from its parent: the parent no longer waits for it
// or cancels it, and structured concurrency is gone.
viewModelScope.launch(NonCancellable) { heavyWork() }

// ❌ Makes the entire operation unstoppable, which defeats the point of this post.
suspend fun load() = withContext(NonCancellable) {
    api.fetchEverything()
}
Enter fullscreen mode Exit fullscreen mode

NonCancellable is meant for finally blocks. Passing it to launch or async replaces the child's Job, severing the parent-child link that structured concurrency depends on.

6. try/finally and resource release

finally is the right place to release things, and it always runs on cancellation, because cancellation is an exception unwinding the stack. The questions are what you do inside it, and whether you remembered to write one.

Non-suspending cleanup is fine as is

suspend fun importFile(uri: Uri) {
    context.contentResolver.openInputStream(uri)!!.use { input ->   // close() is not suspending
        parser.parse(input)
    }
}
Enter fullscreen mode Exit fullscreen mode

use closes the stream whether the block completes, fails or is cancelled.

Suspending cleanup needs NonCancellable

// ❌ dao.markIdle() is a Room suspend function: it throws in a cancelled coroutine
try {
    dao.markSyncing(id)
    performSync(id)
} finally {
    dao.markIdle(id)
}
Enter fullscreen mode Exit fullscreen mode

The row stays stuck in SYNCING after every cancelled run. Wrap the final call in withContext(NonCancellable), as above.

Callback APIs: always awaitClose

The most common source of a leaked system resource is a callbackFlow that registers a listener and forgets to remove it:

fun ConnectivityManager.networkAvailability(): Flow<Boolean> = callbackFlow {
    val callback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) { trySend(true) }
        override fun onLost(network: Network) { trySend(false) }
    }
    registerDefaultNetworkCallback(callback)

    awaitClose { unregisterNetworkCallback(callback) }   // runs when the collector is cancelled
}.distinctUntilChanged()
Enter fullscreen mode Exit fullscreen mode

awaitClose suspends until the flow's collector goes away, then runs its block, which is exactly where the listener must be removed. Without it, the callback keeps firing and keeps the process busy after the UI is gone. (registerDefaultNetworkCallback requires API 24+; on lower minSdk, register a NetworkRequest with registerNetworkCallback instead. The pattern also needs ACCESS_NETWORK_STATE, and you should also collect it with lifecycle awareness, for example repeatOnLifecycle, so you aren't listening while the app is backgrounded.)

7. Timeouts: withTimeout vs withTimeoutOrNull

Timeouts are cancellation with a clock attached. Both functions cancel their block when the deadline passes, and both are cooperative, so a tight loop inside still needs ensureActive() to honor the deadline.

timeouts

withTimeoutOrNull for "nice to have"

suspend fun loadConfig(): Config {
    val fresh = withTimeoutOrNull(3.seconds) { remote.fetchConfig() }
    return fresh ?: cache.lastKnownConfig()
}
Enter fullscreen mode Exit fullscreen mode

A slow network is an expected condition here. A null is just another value, and the call site stays free of try/catch. One caveat: if the block itself can legitimately return null, you can no longer tell "timed out" from "succeeded with null". In that case use withTimeout.

withTimeout for "must handle"

suspend fun checkout(cart: Cart): Receipt =
    try {
        withTimeout(10.seconds) { payments.charge(cart) }
    } catch (e: TimeoutCancellationException) {
        throw CheckoutTimedOut(cart.id, e)      // translate into a domain error
    }
Enter fullscreen mode Exit fullscreen mode

The subtlety that bites in production

TimeoutCancellationException extends CancellationException. That has two practical consequences:

  1. Your own coroutine isn’t cancelled by it. If you catch it at the call site, as above, you’re fine and execution continues normally.
  2. If you let it escape a launch unhandled, the coroutine quietly ends as cancelled, with no crash and no log. A timeout inside a fire-and-forget job simply disappears. Catch it, or use withTimeoutOrNull, so the failure is visible.

Remember also the interplay with Section 4: a blanket catch (e: CancellationException) { throw e } inside the timed block is correct, but a blanket catch (e: Exception) around the whole withTimeout call will treat a timeout as an ordinary failure, which may or may not be what you intend. Decide deliberately.

8. Testing cancellation with runTest

Cancellation bugs are invisible to ordinary tests because the happy path still passes. You have to cancel on purpose and then assert that work stopped. With runTest and virtual time this is fast and deterministic.

Add kotlinx-coroutines-test to your test dependencies.

Test 1: a loop stops after cancel

import kotlin.time.Duration.Companion.seconds

class PollerTest {

    @Test
    fun `poller stops producing after its job is cancelled`() = runTest {
        var ticks = 0
        val job = launch {
            while (true) {
                ticks++
                delay(1.seconds)
            }
        }

        advanceTimeBy(3.5.seconds)
        runCurrent()
        job.cancelAndJoin()

        val atCancel = ticks
        assertTrue(atCancel > 0)

        advanceTimeBy(30.seconds)        // virtual time: costs nothing
        assertEquals(atCancel, ticks)    // no further ticks
    }
}
Enter fullscreen mode Exit fullscreen mode

Test 2: a regression test for the swallowed exception

The test fake must guard against the hot loop from Section 4. If cancellation is swallowed, a naive test would hang the test thread, so make the fake fail loudly instead. Note that it throws AssertionError (an Error, not an Exception), so the buggy catch (e: Exception) cannot hide it:

class FakePendingApi : PendingApi {
    var calls = 0

    override suspend fun fetchPending(): List<Pending> {
        if (++calls > 1_000) throw AssertionError("still calling the API after cancellation")
        delay(1.seconds)
        return emptyList()
    }
}

class SyncWorkerTest {

    @Test
    fun `sync loop terminates promptly when cancelled`() = runTest {
        val api = FakePendingApi()
        val worker = SyncWorker(api, FakePendingDao(), NoopLogger)

        val job = launch { worker.runForever() }
        runCurrent()                       // let it reach its first delay
        job.cancelAndJoin()

        assertTrue(job.isCancelled)
        val atCancel = api.calls
        advanceUntilIdle()
        assertEquals(atCancel, api.calls)
    }
}
Enter fullscreen mode Exit fullscreen mode

Run this against the buggy version from Section 4 and it fails with the AssertionError. Run it against the fixed version and it passes.

Test 3: cleanup still runs

@Test
fun `staged draft is discarded even when the upload is cancelled`() = runTest {
    val store = FakeDraftStore()
    val uploader = DraftUploader(store, FakeDraftApi(uploadNeverCompletes = true))

    val job = launch { uploader.upload(Draft("d1")) }
    runCurrent()
    job.cancelAndJoin()

    assertTrue(store.staged.isEmpty())   // finally { withContext(NonCancellable) { ... } } ran
}
Enter fullscreen mode Exit fullscreen mode

Test 4: timeouts in virtual time

@Test
fun `config falls back to cache after three seconds`() = runTest {
    val config = loadConfig(
        fetch = { delay(10.seconds); Config("fresh") },
        cached = Config("cached"),
    )
    assertEquals("cached", config.name)
    assertEquals(3_000, currentTime)     // virtual clock advanced exactly to the deadline
}
Enter fullscreen mode Exit fullscreen mode

(This assumes loadConfig takes the fetch function and a cached value as parameters, which also happens to make it trivially testable.)

A review checklist you can paste into your PR template

  • [ ] Every loop that doesn’t suspend has an ensureActive() (or equivalent) at a reasonable interval.
  • [ ] No catch (e: Exception) or Throwable / runCatching in suspending code without rethrowing CancellationException.
  • [ ] Blocking I/O is wrapped in runInterruptible, or cancelled via the library's own cancel().
  • [ ] Suspending cleanup in finally uses withContext(NonCancellable) with a timeout, and nothing else does.
  • [ ] No launch(NonCancellable) anywhere.
  • [ ] Every callbackFlow ends with awaitClose { ...unregister... }.
  • [ ] Timeouts are withTimeoutOrNull for fallbacks and withTimeout plus an explicit catch for failures.
  • [ ] There is at least one runTest that cancels the job and asserts that work stopped.

🔚 Takeaways

Cancellation in Kotlin is a protocol, not a mechanism. The runtime offers a signal, and your code decides whether to honor it. Most battery-burning coroutine bugs come down to a single sentence: a cancelled job reached no checkpoint, or something swallowed the exception that was meant to stop it. Add checkpoints where there are none, let CancellationException pass through every catch, keep NonCancellable tiny, and write one test that proves the work actually stops.

📱 New to Jetpack Compose? Start Here

If you’re coming from the classic Android View system — XML layouts, findViewById, RecyclerView adapters — and want a clear, no-jargon path into Jetpack Compose, I recommend "Learning Jetpack Compose: Your Practical Guide from the Android View System to Modern Declarative UI." Every chapter starts from something you already know and shows its Compose equivalent side by side, building up to a full capstone: a real Notes app. Once you're comfortable and want to go deeper — the Composition tree, recomposition internals, the runtime itself — "Mastering Jetpack Compose Internals" is the natural next step.


Originally published on Medium.

Top comments (0)