Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

withContext ingnores cancellation from withTimeout when the dispatcher cannot execute the body #4382

Open
zuevmaxim opened this issue Mar 11, 2025 · 0 comments
Labels

Comments

@zuevmaxim
Copy link
Contributor

Describe the bug

The following code hangs, while I expected it to output Timeout. When I uncomment the commented code, it works as I expected, so withContext handles timeouts differently. I wonder if it can be handled correctly without a deadlock here.

Provide a Reproducer

package kt.coroutines

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.util.concurrent.Executors
import kotlin.coroutines.resume

fun main() {
    val executor = Executors.newSingleThreadExecutor { r -> Thread(r, "MyThread") }
    val dispatcher = executor.asCoroutineDispatcher()
    runBlocking(dispatcher) {
        runBlocking { // block on the dispatcher thread
            val c = Channel<String>()
            launch(Dispatchers.Default) {
                try {
                    withTimeout(1000) {
//                        suspendCancellableCoroutine { cont ->
//                            executor.submit {
//                                c.trySend("Switched to dispatcher")
//                                cont.resume(Unit)
//                            }
//                        }
                        withContext(dispatcher) { // cannot switch to dispatcher as it is locked, but can it timeout?
                            c.send("Switched to dispatcher")
                        }
                    }
                } catch (_: TimeoutCancellationException) {
                    c.send("Timeout")
                }
            }
            println(c.receive())
        }
    }
    executor.shutdown()
}

version 1.9.0

@zuevmaxim zuevmaxim added the bug label Mar 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant