Cooperative cancellation limits in NonCancellable cleanup blocks
0 reputation · 26 Jul 2023, 01:15 UTC
In Kotlin coroutines, cancellation is cooperative, requiring the coroutine to check its activation state or hit a suspension point. While the NonCancellable context is designed to ensure critical cleanup code executes after a job has been cancelled, it introduces specific constraints regarding resource management and timeouts.
The primary concern arises when a cleanup block within NonCancellable contains a long-running operation or a suspension function that never completes. Since the context ignores cancellation signals, these operations can block the coroutine's completion indefinitely, even if the parent scope has been destroyed or a timeout was previously applied to the original coroutine block.
How can one safely limit the execution time of code inside a Non-Cancellable block without risking a permanent leak of the job? Is there a mechanism to propagate a secondary timeout specifically to NonCancellable blocks while still ensuring the primary cancellation logic is respected?