Middle+
Are there cases when we cannot cancel coroutines?
sobes.tech AI
Answer from AI
Yes, they exist.
Examples of such cases:
- A coroutine performs a long computational task without regular cancellation checks. The coroutine checks
isActiveonly when suspended (suspending). If the task does not suspend (for example, a long loop or mathematical calculations), it will not see the cancellation request. - Cancellation exceptions are not handled (for example,
CancellationExceptionis not caught). The coroutine may finish, but the parent coroutine or task manager will not be aware of its cancellation, and resources may not be released properly. - Use of non-cooperative dispatchers, such as
Dispatchers.Unconfinedor a thread pool dispatcher that does not support Cooperative Cancellation. Although aCancellationExceptionwill still be thrown, behavior can be unpredictable. - Using blocking I/O operations without wrapping them in suspending functions (for example, reading from
InputStreamin a loop without usingwithContext(Dispatchers.IO)and suspending methods). A blocking operation does not check the coroutine's state and does not throwCancellationException.
For cooperative cancellation, a coroutine should:
- Use a dispatcher that supports
Cooperative Cancellation(for example,Dispatchers.Default,Dispatchers.IO,Dispatchers.Main). - Regularly check
isActiveor use suspending functions that do this for it. - Properly handle
CancellationException.