Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 134 ยท Coroutines

Cancellation and Timeouts

Learn how Kotlin coroutine cancellation really works - cooperative checks, isActive, ensureActive, finally blocks, NonCancellable cleanup, withTimeout and withTimeoutOrNull, with runnable examples.

Starting work is easy. The hard part of concurrent programming is stopping it: the user leaves the screen, a request takes too long, a sibling task failed and the result is no longer needed. Kotlin coroutines make stopping a first-class feature, and it works everywhere in the same way. But it is cooperative: a coroutine is not killed from the outside, it is asked to stop, and it must notice.

This lesson shows what cancellation is, why a loop that never suspends cannot be cancelled, how to clean up properly, and how timeouts are built on the same mechanism. It continues from structured concurrency, where you saw that cancellation travels down the job tree.

Cancelling a job

launch returns a Job. Calling job.cancel() marks it as cancelled; the coroutine stops at its next suspension point (such as delay, await, receive), where a special exception is thrown inside it. join() waits until the coroutine has really finished, and cancelAndJoin() does both.

Kotlin Cancel a launched coroutine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The job printed steps 0, 1 and 2, then was cancelled while it was sleeping in delay. The line all steps done never appears. After cancelAndJoin the job is both cancelled and completed: completed means "no longer running", cancelled tells you why.

How it works: CancellationException

Cancellation is implemented with an exception, CancellationException, thrown at a suspension point. It is a normal exception that travels up and runs finally blocks, but the coroutine machinery treats it as a quiet signal: it is not reported as an error and it does not fail the parent. You can see it if you catch it:

Kotlin The exception behind a cancel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The real class is JobCancellationException, a subclass of CancellationException, so catching the parent type works. Notice throw e. If you catch CancellationException (or catch Exception or Throwable, which includes it) and do not rethrow, the coroutine carries on as if nothing happened. That is one of the most common coroutine bugs and it is covered again in exceptions in coroutines.

Cancellation is cooperative

A coroutine can only be cancelled where it checks. All the suspend functions in kotlinx.coroutines (delay, yield, await, withContext, channel and flow operations) check. A plain loop of computation does not. The next example cancels a busy loop that never suspends, and the cancel does nothing until the loop ends on its own.

Kotlin A busy loop ignores cancel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The loop printed still active = false: the job was cancelled after 50 ms, yet the loop ran to its natural end. Nothing in it looked at the cancellation state. There are three ways to make code cancellable.

Check isActive

Inside a coroutine, isActive is true until the job is cancelled. Use it as the loop condition:

Kotlin Loop on isActive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The loop exits shortly after cancel(). Using isActive as the condition is neat, but it exits normally: the code after the loop still runs, and the job ends as cancelled only because it was cancelled before.

ensureActive and yield

ensureActive() throws CancellationException if the job has been cancelled, so it works like a built-in checkpoint. yield() also checks, and in addition lets other coroutines on the same dispatcher run. Put one of them inside long computations:

Kotlin ensureActive checkpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The search over two billion numbers would take many minutes, but the checkpoint at the top of each iteration turns cancellation into a prompt stop. Inside a plain suspend function use currentCoroutineContext().ensureActive(); inside a coroutine builder lambda you can call ensureActive() directly.

Checking on every iteration costs a few nanoseconds. For very tight loops, check every few thousand iterations, for example if (n % 10_000 == 0) ensureActive().

Cleaning up with finally

When a coroutine is cancelled, finally blocks run, so they are the place to release resources: close a file, unregister a listener, reset a flag.

Kotlin finally runs on cancel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The same works with use on closeable objects (see resources and use), which is finally in disguise.

Suspending inside finally: NonCancellable

There is a catch. The coroutine is already cancelled while the finally block runs, so any suspension point inside it throws CancellationException straight away. If cleanup itself must suspend (flush to a slow store, send a goodbye message), run it in withContext(NonCancellable):

Kotlin Suspending cleanup (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Only main done is printed. The delay(50) in finally threw CancellationException, so the following line never ran, and nothing told you. Now the fix:

Kotlin NonCancellable cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Now cleanup finished is printed before main done, because cancelAndJoin waits for the finally block. Use NonCancellable only for short, essential cleanup. A cleanup that can hang forever defeats the purpose of cancellation.

Timeouts

Often cancellation is triggered by time: give a task two seconds, then stop. withTimeout(ms) runs a block and cancels it when the time runs out. It throws TimeoutCancellationException (a subclass of CancellationException) to the caller:

Kotlin withTimeout (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program ends with a stack trace and the message Timed out waiting for 200 ms from kotlinx.coroutines.TimeoutCancellationException. Because the exception is thrown to the caller, you handle it with try/catch, or you use the sibling function withTimeoutOrNull, which returns null instead of throwing:

Kotlin withTimeoutOrNull

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

withTimeoutOrNull is the more convenient choice when a timeout is an expected outcome, such as a fallback to cached data. Use withTimeout when running out of time is a real error.

Timeouts are ordinary cancellation, so everything above applies: a block that never reaches a suspension point cannot be interrupted, and resources inside it are released by finally.

Beware of resources inside a timeout

The timeout exception arrives asynchronously, so the block can be cancelled between acquiring a resource and handing it on. Do not assign a resource to an outside variable inside withTimeout. Create and close it entirely inside the block, using try/finally or use.

Cancelling a whole scope

A scope created with CoroutineScope(...) can be cancelled as a unit with scope.cancel(). After that, the scope's job is cancelled for good and cannot start new coroutines. To cancel only the children but keep the scope usable, call scope.coroutineContext.job.cancelChildren().

Kotlin cancelChildren keeps the scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After cancelChildren() the scope accepted a new coroutine. After scope.cancel() a new coroutine is cancelled before it starts.

Common mistakes

  • Swallowing CancellationException with catch (e: Exception). Rethrow it, or catch narrower types. runCatching has the same trap, because it catches everything.
  • Busy loops without a check. Computation never stops unless it calls isActive, ensureActive or yield.
  • Blocking calls. Thread.sleep and blocking I/O are not cancellable by coroutine cancellation. Use delay, or run the blocking call in withContext(Dispatchers.IO) and accept that it finishes first.
  • Suspending in finally without NonCancellable.
  • Using timeouts as a retry strategy without limits. A timeout stops waiting; the server may still process the request.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does cancelling a coroutine that runs a tight loop without suspension points have no effect?

    Cancellation is cooperative. The coroutine stops only at suspension points or explicit checks such as isActive and ensureActive.
  2. 2. Which exception is thrown inside a coroutine when it is cancelled?

    The coroutine is cancelled by throwing CancellationException at a suspension point; the exception is treated as a normal, quiet signal.
  3. 3. You call delay(50) inside a finally block of a cancelled coroutine. What happens?

    The job is already cancelled, so suspension points throw straight away. withContext(NonCancellable) allows suspending cleanup.
  4. 4. What does withTimeoutOrNull(100) { delay(500); 1 } return?

    withTimeoutOrNull returns null when the time runs out instead of throwing.
  5. 5. Which call both cancels a job and waits until it has finished its cleanup?

    cancelAndJoin() is cancel() followed by join(), so finally blocks have completed when it returns.

Summary

  • cancel() asks a coroutine to stop; it stops at the next suspension point, where CancellationException is thrown.
  • Cancellation is cooperative: tight loops need isActive, ensureActive() or yield().
  • Use finally (or use) for cleanup; suspend inside it only with withContext(NonCancellable).
  • Never swallow CancellationException; rethrow it.
  • withTimeout throws TimeoutCancellationException; withTimeoutOrNull returns null.
  • cancelAndJoin() cancels and waits; cancelChildren() keeps a scope usable.

Next: Dispatchers and Context