Stephen Edwards
02/04/2021, 3:40 PMfun coroutinesAreSometimesDispatchedOntoDaemonThreads() = runBlocking<Unit> {
println("Main. Thread: ${Thread.currentThread()}. isDaemon? ${Thread.currentThread().isDaemon}")
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
println("Coroutine. Thread: ${Thread.currentThread()}. isDaemon? ${Thread.currentThread().isDaemon}")
}
}
Prints:
Main. Thread: Thread[main,5,main]. isDaemon? false
Coroutine. Thread: Thread[DefaultDispatcher-worker-1,5,main]. isDaemon? true
Dispatchers.Default
and only ends up happenign because GlobalScope
uses that dispatcher when not otherwise specified?Dispatchers.Default
coroutines use daemon threads?Niklas Gürtler
02/04/2021, 7:48 PMZach Klippenstein (he/him) [MOD]
02/04/2021, 7:59 PM<http://Dispatchers.IO|Dispatchers.IO>
, not because it uses worker threads. You can create a CoroutineDispatcher
from any regular java thread pool.
As for the purpose of the default dispatcher, I think that’s pretty well-documented in the official kotlin coroutine docs. This question is specifically about why the default dispatcher’s thread pool threads are daemon threads, instead of just regular threads. Daemon threads are a JVM concept, see the java docs for more.