Shivang Tripathi
Shivang Tripathi

Reputation: 51

How to figure out the thread pool of thread [Kotlin]?

Consider the following piece of code:

suspend fun childTaskExecutor()  {
    GlobalScope.future(Dispatchers.Default) {
        val currentThread = Thread.currentThread()
        logger.info("[childTaskExecutor] running on ${currentThread.name} group : ${currentThread.threadGroup}")
    }.awaitOrNull()
}

When I run this the output is: [childTaskExecutor] running on DefaultDispatcher-worker-9 group : java.lang.ThreadGroup[name=main,maxpri=10]

When I change the context to Dispatchers.IO the output is: running on DefaultDispatcher-worker-6 group : java.lang.ThreadGroup[name=main,maxpri=10]

I want to be able to figure out which thread pool does the thread belong to (IO, Default, Unconfined). Any way to do that?

Upvotes: 2

Views: 1082

Answers (1)

marstran
marstran

Reputation: 28036

A coroutine dispatcher is not quite the same as a thread pool. A coroutine dispatcher is backed by a thread pool, but each of them don't need to use a different thread pool. In fact, the threadpools of some of the built-in dispatchers actually overlap. That's why you see the same DefaultDispatcher-thread even when you use Dispatchers.IO.

This layout with overlapping thread pools make coroutines more efficient. The runtime doesn't necessarily have to switch threads when you switch from Dispatchers.Default to Dispatchers.IO.

If you want to see which coroutine dispatcher you are currently on, you can fetch it from the coroutine context. Like this:

// Prints the name of the coroutine dispatcher.
println(coroutineContext[CoroutineDispatcher])

Note that the companion object you access with CoroutineDispatcher is currently experimental API, so you need to opt in to use it.

Upvotes: 1

Related Questions