Skip to content

Commit a79db37

Browse files
authored
Create Dispatcher.Default threads with the same context classloader a… (#3877)
* Create Dispatcher.Default threads with the same context classloader as the dispatcher itself In order to properly operate in modularized on a classloader level environments with the absence of other workarounds (i.e. supplying application-specific thread factory) * Do the same trick for DefaultExecutor Fixes #3832
1 parent 00a0767 commit a79db37

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

kotlinx-coroutines-core/jvm/src/DefaultExecutor.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,13 @@ internal actual object DefaultExecutor : EventLoopImplBase(), Runnable {
135135
private fun createThreadSync(): Thread {
136136
return _thread ?: Thread(this, THREAD_NAME).apply {
137137
_thread = this
138+
/*
139+
* `DefaultExecutor` is a global singleton that creates its thread lazily.
140+
* To isolate the classloaders properly, we are inherting the context classloader from
141+
* the singleton itself instead of using parent' thread one
142+
* in order not to accidentally capture temporary application classloader.
143+
*/
144+
contextClassLoader = this@DefaultExecutor.javaClass.classLoader
138145
isDaemon = true
139146
start()
140147
}

kotlinx-coroutines-core/jvm/src/scheduling/CoroutineScheduler.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,13 @@ internal class CoroutineScheduler(
593593
internal inner class Worker private constructor() : Thread() {
594594
init {
595595
isDaemon = true
596+
/*
597+
* `Dispatchers.Default` is used as *the* dispatcher in the containerized environments,
598+
* isolated by their own classloaders. Workers are populated lazily, thus we are inheriting
599+
* `Dispatchers.Default` context class loader here instead of using parent' thread one
600+
* in order not to accidentally capture temporary application classloader.
601+
*/
602+
contextClassLoader = this@CoroutineScheduler.javaClass.classLoader
596603
}
597604

598605
// guarded by scheduler lock, index in workers array, 0 when not in array (terminated)

0 commit comments

Comments
 (0)