Kieran Wallbanks
01/23/2025, 4:37 PMlaunch
is being blocked from executing due to not enough free threads? We're running into a weird issue where sometimes it seems like launches just take longer than they should to get started and am not really sure how to debug this.Daniel Pitts
01/23/2025, 6:25 PMKieran Wallbanks
01/24/2025, 11:51 AMkevin.cianfarini
01/24/2025, 4:06 PMTimeSource.Monotonic
val mark = TimeSource.Monotonic.markNow()
launch {
val elapsed: Duration = mark.elapsedNow()
}
This won’t work for everything because a dispatcher doesn’t just dispatch launched coroutines. It dispatches every single block of code between suspension points. You might even be able to wrap dispatchers with something similar to the above to provide diagnostic information.kevin.cianfarini
01/24/2025, 4:11 PMclass DiagnosticDispatcher(private val delegate: CoroutineDispatcher) : CoroutineDispatcher {
override fun dispatch(context: CoroutineContext, block: Runnable) {
val mark = TimeSource.Monotonic.markNow()
val diagnosticBlock = Runnable {
val duration = mark.elapsedNow()
println(duration)
block.run()
}
delegate.dispatch(context, diagnosticBlock)
}
}
kevin.cianfarini
01/24/2025, 4:12 PMkevin.cianfarini
01/24/2025, 4:24 PMfinal class DiagnosticDispatcher(private val delegate: CoroutineDispatcher) : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
val mark = TimeSource.Monotonic.markNow()
val diagnosticBlock = Runnable {
val duration = mark.elapsedNow()
println(duration)
block.run()
}
delegate.dispatch(context, diagnosticBlock)
}
}
@OptIn(ExperimentalStdlibApi::class)
fun main() = runBlocking {
val dispatcher = currentCoroutineContext()[CoroutineDispatcher]!!
withContext(DiagnosticDispatcher(dispatcher)) {
flow {
while (true) {
val value = Random.nextLong(until = 5_000)
yield()
emit(value)
}
}.take(10).collect()
}
}
With the following output:
3.015291ms
20.5us
13.166us
6.166us
5us
4.584us
4.5us
4.167us
4.208us
5us
4.375us
Kieran Wallbanks
01/29/2025, 11:17 AMkevin.cianfarini
01/29/2025, 1:38 PM