- Cancellation and timeouts
- Cancelling coroutine execution
- Cancellation is cooperative
- Making computation code cancellable
- Closing resources with finally
- Run non-cancellable block
- Timeout
- Asynchronous timeout and resources
- Как закрыть корутину kotlin
- Обработка исключения CancellationException
- Отмена выполнения async-корутины
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:
import kotlinx.coroutines.* fun main() = runBlocking < //sampleStart val job = launch < repeat(1000) < i ->println(«job: I’m sleeping $i . «) delay(500L) > > delay(1300L) // delay a bit println(«main: I’m tired of waiting!») job.cancel() // cancels the job job.join() // waits for job’s completion println(«main: Now I can quit.») //sampleEnd >
You can get the full code here.
It produces the following output:
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.
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:
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.
The same problem can be observed by catching a CancellationException and not rethrowing it:
import kotlinx.coroutines.* fun main() = runBlocking < //sampleStart val job = launch(Dispatchers.Default) < repeat(5) < i ->try < // print a message twice a second println("job: I'm sleeping $i . ") delay(500) >catch (e: Exception) < // log the exception println(e) >> > delay(1300L) // delay a bit println(«main: I’m tired of waiting!») job.cancelAndJoin() // cancels the job and waits for its completion println(«main: Now I can quit.») //sampleEnd >
You can get the full code here.
While catching Exception is an anti-pattern, this issue may surface in more subtle ways, like when using the runCatching function, which does not rethrow CancellationException.
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.
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, the try <. >finally <. >expression and Kotlin’s use function execute their finalization actions normally when a coroutine is cancelled:
import kotlinx.coroutines.* fun main() = runBlocking < //sampleStart val job = launch < try < repeat(1000) < i ->println(«job: I’m sleeping $i . «) delay(500L) > > finally < println("job: I'm running finally") >> delay(1300L) // delay a bit println(«main: I’m tired of waiting!») job.cancelAndJoin() // cancels the job and waits for its completion println(«main: Now I can quit.») //sampleEnd >
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:
job: I’m sleeping 0 . job: I’m sleeping 1 . job: I’m sleeping 2 . main: I’m tired of waiting! job: I’m running finally 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:
import kotlinx.coroutines.* fun main() = runBlocking < //sampleStart val job = launch < try < repeat(1000) < i ->println(«job: I’m sleeping $i . «) delay(500L) > > finally < withContext(NonCancellable) < println("job: I'm running finally") delay(1000L) println("job: And I've just delayed for 1 sec because I'm non-cancellable") >> > delay(1300L) // delay a bit println(«main: I’m tired of waiting!») job.cancelAndJoin() // cancels the job and waits for its completion println(«main: Now I can quit.») //sampleEnd >
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:
import kotlinx.coroutines.* fun main() = runBlocking < //sampleStart withTimeout(1300L) < repeat(1000) < i ->println(«I’m sleeping $i . «) delay(500L) > > //sampleEnd >
You can get the full code here.
It produces the following output:
I’m sleeping 0 . I’m sleeping 1 . I’m sleeping 2 . 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:
import kotlinx.coroutines.* fun main() = runBlocking < //sampleStart val result = withTimeoutOrNull(1300L) < repeat(1000) < i ->println(«I’m sleeping $i . «) delay(500L) > «Done» // will get cancelled before it produces this result > println(«Result is $result») //sampleEnd >
You can get the full code here.
There is no longer an exception when running this code:
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 the counter in its close function. Now let us create a lot of coroutines, each of which creates a Resource at the end of the withTimeout block and releases the resource outside the block. We add a small delay so that it is more likely that the timeout occurs right when the withTimeout block is already finished, which will cause a resource leak.
import kotlinx.coroutines.* //sampleStart var acquired = 0 class Resource < init < acquired++ >// Acquire the resource fun close() < acquired-- >// Release the resource > fun main() < runBlocking < repeat(10_000) < // Launch 10K coroutines launch < val resource = withTimeout(60) < // Timeout of 60 ms delay(50) // Delay for 50 ms Resource() // Acquire a resource and return it from withTimeout block >resource.close() // Release the resource > > > // Outside of runBlocking all coroutines have completed println(acquired) // Print the number of resources still acquired > //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 the timeout in this example to actually see non-zero values.
Note that incrementing and decrementing acquired counter here from 10K coroutines is completely thread-safe, since it always happens from the same thread, the one used by runBlocking . More on that will be explained in the chapter on coroutine context.
To work around this problem you can store a reference to the resource in a variable instead of returning it from the withTimeout block.
import kotlinx.coroutines.* var acquired = 0 class Resource < init < acquired++ >// Acquire the resource fun close() < acquired-- >// Release the resource > fun main() < //sampleStart runBlocking < repeat(10_000) < // Launch 10K coroutines launch < var resource: Resource? = null // Not acquired yet try < withTimeout(60) < // Timeout of 60 ms delay(50) // Delay for 50 ms resource = Resource() // Store a resource to the variable if acquired >// We can do something else with the resource here > finally < resource?.close() // Release the resource if it was acquired >> > > // Outside of runBlocking all coroutines have completed println(acquired) // Print the number of resources still acquired //sampleEnd >
You can get the full code here.
This example always prints zero. Resources do not leak.
Как закрыть корутину kotlin
При работе приложения может сложиться необходимость отменить выполнение корутины. Например, в мобильном приложении запущена корутина для загрузки данных с некоторого интернет-ресуса, но пользователь решил перейти к другой странице приложения, и ему больше не нужны эти данные. В этом случае чтобы зря не тратить ресурсу системы, мы можем предусмотреть отмену выполнения корутины.
Для отмены выполнения корутины у объекта Job может применяться метод cancel() :
import kotlinx.coroutines.* suspend fun main() = coroutineScope < val downloader: Job = launch< println("Начинаем загрузку файлов") for(i in 1..5)< println("Загружен файл $i") delay(500L) >> delay(800L) // установим задержку, чтобы несколько файлов загрузились println("Надоело ждать, пока все файлы загрузятся. Прерву-ка я загрузку. ") downloader.cancel() // отменяем корутину downloader.join() // ожидаем завершения корутины println("Работа программы завершена") >
В данном случае определена корутина, которая имитирует загрузку файлов. В цикле пробегаемся от 1 до 5 и условно загружаем пять файлов.
Далее вызов метода downloader.cancel() сигнализирует корутине, что надо прервать выполнение. Затем с помощью метода join() ожидаем завершения корутина, которая прервана. В итоге получим консольный вывод наподобие следующего:
Начинаем загрузку файлов Загружен файл 1 Загружен файл 2 Надоело ждать, пока все файлы загрузятся. Прерву-ка я загрузку. Работа программы завершена
Также вместо двух методов cancel() и join() можно использовать один сборный метод cancelAndJoin() :
import kotlinx.coroutines.* suspend fun main() = coroutineScope < val downloader: Job = launch< println("Начинаем загрузку файлов") for(i in 1..5)< println("Загружен файл $i") delay(500L) >> delay(800L) println("Надоело ждать, пока все файлы загрузятся. Прерву-ка я загрузку. ") downloader.cancelAndJoin() // отменяем корутину и ожидаем ее завершения println("Работа программы завершена") >
Обработка исключения CancellationException
Все suspend-функции в пакете kotlinx.coroutines являются прерываемыми (cancellable). Это значит, что они проверяют, прервана ли корутина. И если ее выполнение прервано, они генерируют исключение типа CancellationException . И в самой корутине мы можем перехватить это исключение, чтобы обработать отмену корутины. Например:
import kotlinx.coroutines.* suspend fun main() = coroutineScope < val downloader: Job = launch< try < println("Начинаем загрузку файлов") for(i in 1..5)< println("Загружен файл $i") delay(500L) >> catch (e: CancellationException ) < println("Загрузка файлов прервана") >finally < println("Загрузка завершена") >> delay(800L) println("Надоело ждать. Прерву-ка я загрузку. ") downloader.cancelAndJoin() // отменяем корутину и ожидаем ее завершения println("Работа программы завершена") >
Здесь код выполнения корутины обернут в конструкцию try . Если корутина будет прервана извне, то с помощью блока catch и перехвата исключения CancellationException мы сможем обработать отмену корутины.
И если нам надо выполнить некоторые завершающие действия, например, освободить используемые в корутине ресурсы — закрыть файлы, различные подключения к внешним ресурсам, то это можно сделать в блоке finally . Но в данном случае в этом блоке просто выводим диагностическое сообщение.
В итоге при вызове метода downloader.cancel() производейт отмена корутины. Будет сгенерировано исключение, и в корутине в блоке catch мы сможем ее обработать. В итоге получим следующий консольный вывод:
Начинаем загрузку файлов Загружен файл 1 Загружен файл 2 Надоело ждать. Прерву-ка я загрузку. Загрузка файлов прервана Загрузка завершена Работа программы завершена
Отмена выполнения async-корутины
Подобным образом можно отменять выполнение и корутин, создаваемых с помощью функции async() . В этом случае обычно вызов метода await() помещается в блок try:
import kotlinx.coroutines.* suspend fun main() = coroutineScope < // создаем и запускаем корутину val message = async < getMessage() >// отмена корутины message.cancelAndJoin() try < // ожидаем получение результата println("message: $") > catch (e:CancellationException) < println("Coroutine has been canceled") >println(«Program has finished») > suspend fun getMessage() : String
Консольный вывод программы:
Coroutine has been canceled Program has finished