I’m hitting a weird issue with nested `withTimeout...
# coroutines
c
I’m hitting a weird issue with nested
withTimeout
, it seems to prevent closing the dispatcher being used. Anyone have any ideas why it might not work? (The code is a simplified example of the real code)
Copy code
@Test
    fun nestedTimeouts() = runBlocking {
        val disp: CloseableCoroutineDispatcher = newSingleThreadContext("my-test")
        val result = withTimeout(30.seconds) {
            withContext(disp) {
                // Disabling the inner timeout will make it work correctly
                withTimeout(30.seconds) {
                    "Hello"
                }
            }
        }
        println(result) // Print "Hello"
        disp.close()
        println("Dispatcher closed: $disp") // We never reach here if the inner timeout is enabled
    }
It only deadlocks on Darwin, JVM platforms work fine 🤔
d
Does it work if you remove the outer timeout?
c
No, that also deadlocks
This is on Kotlin 1.8.20 with Coroutines 1.6.4
d
Could you try with coroutines 1.7.1? We reworked
newSingleThreadContext
quite a bit in 1.7.0, so maybe the issue is fixed already.
Nevermind, I checked it, and the issue is still there. Thanks for the report!
Workaround: use
newFixedThreadPool(1, "my-test")
instead.
c
Uhhh, that works. Thanks… but I’m a bit surprised since
newSingleThreadContext
just seems to delegate to that?
Copy code
public actual fun newSingleThreadContext(name: String): ExecutorCoroutineDispatcher =
    newFixedThreadPoolContext(1, name)
d
c
Ah, I might have gone to the wrong implementation 🙈
Thanks a lot for the quick help 🙏