In many cases, we have coroutines that are long-lasting, for example, if we have an actor or a producer and we want to specify which name should be used for them when the VM flag is passed. We can pass a parameter to the coroutine builders to specify the name that we want, and then we can easily find the entries in the log for that coroutine. Let's do a simple implementation of this:
val pool = newFixedThreadPoolContext(3, "myPool")
val ctx = newSingleThreadContext("ctx")
withContext(pool + CoroutineName("main")) {
println("Running in ${threadName()}")
withContext(ctx + CoroutineName("inner")) {
println("Switching to ${threadName()}")
}
}
This example uses CoroutineName to give a specific name to the coroutine. Because CoroutineName is a context element, it can be set using the plus operator. If we execute this code, Thread.currentThread().name will contain the name of the thread pool, the number of the thread in the pool—unless it is a single thread context—and the numeric identifier of the coroutine: