Identifying a coroutine in the logs

As you already know, you can create hundreds or thousands of coroutines, and those can be executed in one or more threads during their life cycle. Some of those coroutines will last for a long time, while others will be short-lived, maybe because they are tied to a temporary task. So, during debugging, it becomes a necessity to identify them.

Consider this simple application:

val pool = newFixedThreadPoolContext(3, "myPool")
val ctx = newSingleThreadContext("ctx")

val tasks = mutableListOf<Deferred<Unit>>()
for (i in 0..5) {
val task = async(pool) {
println("Processing $i in ${threadName()}")

withContext(ctx) {
println("Step two of $i happening in thread ${threadName()}")
}

println("Finishing $i in ${threadName()}")
}

tasks.add(task)
}

for (task in tasks) {
task.await()
}

The implementation of threadName() looks like this:

private fun threadName() = Thread.currentThread().name

This sample application has a pool of three threads, as well as a single thread context, ctx. Five coroutines are created; each of them will be initially placed in one of the threads of pool, but will soon be moved to the single thread of ctx, and then moved back to one thread in pool. On every context switch, we are printing i, as well as the name of the current thread:

Thanks to the fact that we print i, we can make some sense of this and we can figure out which log entry corresponds to which specific element in our loop. But there are a couple of things that can be improved here:

  • Once you have a certain amount of coroutines, it will be cumbersome to track each coroutine using the parameters that it received
  • If the coroutine doesn't have something that can be used as an unique identifier, you won't be able to precisely identify which entries pertain to a specific one
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.103.96