Setting a specific name

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:

Remember that for the ID to be printed, the -Dkotlinx.coroutines.debug VM flag needs to be set as well. I advise you to always set a coroutine name for long-lasting coroutines like actors and producers.
..................Content has been hidden....................

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