Table of contents

Cancellation and Timeouts

This section covers coroutine cancellation and timeouts.

Cancelling coroutine execution

In a long-running application you might need fine-grained control on your background coroutines. For example, a user might have closed the page that launched a coroutine and now its result is no longer needed and its operation can be cancelled. The launch function returns a Job that can be used to cancel the running coroutine:

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val job = launch {
  5. repeat(1000) { i ->
  6. println("job: I'm sleeping $i ...")
  7. delay(500L)
  8. }
  9. }
  10. delay(1300L) // delay a bit
  11. println("main: I'm tired of waiting!")
  12. job.cancel() // cancels the job
  13. job.join() // waits for job's completion
  14. println("main: Now I can quit.")
  15. //sampleEnd
  16. }

You can get the full code here.

It produces the following output:

  1. job: I'm sleeping 0 ...
  2. job: I'm sleeping 1 ...
  3. job: I'm sleeping 2 ...
  4. main: I'm tired of waiting!
  5. main: Now I can quit.

As soon as main invokes job.cancel, we don’t see any output from the other coroutine because it was cancelled. There is also a Job extension function cancelAndJoin that combines cancel and join invocations.

Cancellation is cooperative

Coroutine cancellation is cooperative. A coroutine code has to cooperate to be cancellable. All the suspending functions in kotlinx.coroutines are cancellable. They check for cancellation of coroutine and throw CancellationException when cancelled. However, if a coroutine is working in a computation and does not check for cancellation, then it cannot be cancelled, like the following example shows:

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val startTime = System.currentTimeMillis()
  5. val job = launch(Dispatchers.Default) {
  6. var nextPrintTime = startTime
  7. var i = 0
  8. while (i < 5) { // computation loop, just wastes CPU
  9. // print a message twice a second
  10. if (System.currentTimeMillis() >= nextPrintTime) {
  11. println("job: I'm sleeping ${i++} ...")
  12. nextPrintTime += 500L
  13. }
  14. }
  15. }
  16. delay(1300L) // delay a bit
  17. println("main: I'm tired of waiting!")
  18. job.cancelAndJoin() // cancels the job and waits for its completion
  19. println("main: Now I can quit.")
  20. //sampleEnd
  21. }

You can get the full code here.

Run it to see that it continues to print “I’m sleeping” even after cancellation until the job completes by itself after five iterations.

Making computation code cancellable

There are two approaches to making computation code cancellable. The first one is to periodically invoke a suspending function that checks for cancellation. There is a yield function that is a good choice for that purpose. The other one is to explicitly check the cancellation status. Let us try the latter approach.

Replace while (i < 5) in the previous example with while (isActive) and rerun it.

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val startTime = System.currentTimeMillis()
  5. val job = launch(Dispatchers.Default) {
  6. var nextPrintTime = startTime
  7. var i = 0
  8. while (isActive) { // cancellable computation loop
  9. // print a message twice a second
  10. if (System.currentTimeMillis() >= nextPrintTime) {
  11. println("job: I'm sleeping ${i++} ...")
  12. nextPrintTime += 500L
  13. }
  14. }
  15. }
  16. delay(1300L) // delay a bit
  17. println("main: I'm tired of waiting!")
  18. job.cancelAndJoin() // cancels the job and waits for its completion
  19. println("main: Now I can quit.")
  20. //sampleEnd
  21. }

You can get the full code here.

As you can see, now this loop is cancelled. isActive is an extension property available inside the coroutine via the CoroutineScope object.

Closing resources with finally

Cancellable suspending functions throw CancellationException on cancellation which can be handled in the usual way. For example, try {...} finally {...} expression and Kotlin use function execute their finalization actions normally when a coroutine is cancelled:

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val job = launch {
  5. try {
  6. repeat(1000) { i ->
  7. println("job: I'm sleeping $i ...")
  8. delay(500L)
  9. }
  10. } finally {
  11. println("job: I'm running finally")
  12. }
  13. }
  14. delay(1300L) // delay a bit
  15. println("main: I'm tired of waiting!")
  16. job.cancelAndJoin() // cancels the job and waits for its completion
  17. println("main: Now I can quit.")
  18. //sampleEnd
  19. }

You can get the full code here.

Both join and cancelAndJoin wait for all finalization actions to complete, so the example above produces the following output:

  1. job: I'm sleeping 0 ...
  2. job: I'm sleeping 1 ...
  3. job: I'm sleeping 2 ...
  4. main: I'm tired of waiting!
  5. job: I'm running finally
  6. main: Now I can quit.

Run non-cancellable block

Any attempt to use a suspending function in the finally block of the previous example causes CancellationException, because the coroutine running this code is cancelled. Usually, this is not a problem, since all well-behaving closing operations (closing a file, cancelling a job, or closing any kind of a communication channel) are usually non-blocking and do not involve any suspending functions. However, in the rare case when you need to suspend in a cancelled coroutine you can wrap the corresponding code in withContext(NonCancellable) {...} using withContext function and NonCancellable context as the following example shows:

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val job = launch {
  5. try {
  6. repeat(1000) { i ->
  7. println("job: I'm sleeping $i ...")
  8. delay(500L)
  9. }
  10. } finally {
  11. withContext(NonCancellable) {
  12. println("job: I'm running finally")
  13. delay(1000L)
  14. println("job: And I've just delayed for 1 sec because I'm non-cancellable")
  15. }
  16. }
  17. }
  18. delay(1300L) // delay a bit
  19. println("main: I'm tired of waiting!")
  20. job.cancelAndJoin() // cancels the job and waits for its completion
  21. println("main: Now I can quit.")
  22. //sampleEnd
  23. }

You can get the full code here.

Timeout

The most obvious practical reason to cancel execution of a coroutine is because its execution time has exceeded some timeout. While you can manually track the reference to the corresponding Job and launch a separate coroutine to cancel the tracked one after delay, there is a ready to use withTimeout function that does it. Look at the following example:

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. withTimeout(1300L) {
  5. repeat(1000) { i ->
  6. println("I'm sleeping $i ...")
  7. delay(500L)
  8. }
  9. }
  10. //sampleEnd
  11. }

You can get the full code here.

It produces the following output:

  1. I'm sleeping 0 ...
  2. I'm sleeping 1 ...
  3. I'm sleeping 2 ...
  4. Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1300 ms

The TimeoutCancellationException that is thrown by withTimeout is a subclass of CancellationException. We have not seen its stack trace printed on the console before. That is because inside a cancelled coroutine CancellationException is considered to be a normal reason for coroutine completion. However, in this example we have used withTimeout right inside the main function.

Since cancellation is just an exception, all resources are closed in the usual way. You can wrap the code with timeout in a try {...} catch (e: TimeoutCancellationException) {...} block if you need to do some additional action specifically on any kind of timeout or use the withTimeoutOrNull function that is similar to withTimeout but returns null on timeout instead of throwing an exception:

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val result = withTimeoutOrNull(1300L) {
  5. repeat(1000) { i ->
  6. println("I'm sleeping $i ...")
  7. delay(500L)
  8. }
  9. "Done" // will get cancelled before it produces this result
  10. }
  11. println("Result is $result")
  12. //sampleEnd
  13. }

You can get the full code here.

There is no longer an exception when running this code:

  1. I'm sleeping 0 ...
  2. I'm sleeping 1 ...
  3. I'm sleeping 2 ...
  4. Result is null

Asynchronous timeout and resources

The timeout event in withTimeout is asynchronous with respect to the code running in its block and may happen at any time, even right before the return from inside of the timeout block. Keep this in mind if you open or acquire some resource inside the block that needs closing or release outside of the block.

For example, here we imitate a closeable resource with the Resource class, that simply keeps track of how many times it was created by incrementing the acquired counter and decrementing this counter from its close function. Let us run a lot of coroutines with the small timeout try acquire this resource from inside of the withTimeout block after a bit of delay and release it from outside.

  1. import kotlinx.coroutines.*
  2. //sampleStart
  3. var acquired = 0
  4. class Resource {
  5. init { acquired++ } // Acquire the resource
  6. fun close() { acquired-- } // Release the resource
  7. }
  8. fun main() {
  9. runBlocking {
  10. repeat(100_000) { // Launch 100K coroutines
  11. launch {
  12. val resource = withTimeout(60) { // Timeout of 60 ms
  13. delay(50) // Delay for 50 ms
  14. Resource() // Acquire a resource and return it from withTimeout block
  15. }
  16. resource.close() // Release the resource
  17. }
  18. }
  19. }
  20. // Outside of runBlocking all coroutines have completed
  21. println(acquired) // Print the number of resources still acquired
  22. }
  23. //sampleEnd

You can get the full code here.

If you run the above code you’ll see that it does not always print zero, though it may depend on the timings of your machine you may need to tweak timeouts in this example to actually see non-zero values.

Note, that incrementing and decrementing acquired counter here from 100K coroutines is completely safe, since it always happens from the same main thread. More on that will be explained in the next chapter on coroutine context.

To workaround this problem you can store a reference to the resource in the variable as opposed to returning it from the withTimeout block.

  1. import kotlinx.coroutines.*
  2. var acquired = 0
  3. class Resource {
  4. init { acquired++ } // Acquire the resource
  5. fun close() { acquired-- } // Release the resource
  6. }
  7. fun main() {
  8. //sampleStart
  9. runBlocking {
  10. repeat(100_000) { // Launch 100K coroutines
  11. launch {
  12. var resource: Resource? = null // Not acquired yet
  13. try {
  14. withTimeout(60) { // Timeout of 60 ms
  15. delay(50) // Delay for 50 ms
  16. resource = Resource() // Store a resource to the variable if acquired
  17. }
  18. // We can do something else with the resource here
  19. } finally {
  20. resource?.close() // Release the resource if it was acquired
  21. }
  22. }
  23. }
  24. }
  25. // Outside of runBlocking all coroutines have completed
  26. println(acquired) // Print the number of resources still acquired
  27. //sampleEnd
  28. }

You can get the full code here.

This example always prints zero. Resources do not leak.