Running this program with kotlinx.coroutines.core 0.23.4:
fun main(args: Array<String>) = runBlocking {
fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
newSingleThreadContext("SINGLE-THREAD").use {
launch(it) {
log("Running in single-thread context.")
withContext(CommonPool) {
log("Running in CommonPool context.")
}
log("Should be back to running in single-thread context.")
}
}.join()
}
produces the output:
[SINGLE-THREAD @coroutine#2] Running in single-thread context.
[ForkJoinPool.commonPool-worker-25 @coroutine#2] Running in CommonPool context.
[kotlinx.coroutines.DefaultExecutor @coroutine#2] Should be back to running in single-thread context.
instead of the expected output:
[SINGLE-THREAD @coroutine#2] Running in single-thread context.
[ForkJoinPool.commonPool-worker-25 @coroutine#2] Running in CommonPool context.
[SINGLE-THREAD @coroutine#2] Should be back to running in single-thread context.
It seems that withContext is not resetting the context properly.
Here is what is going on.newSingleThreadContext(...).use { ... } would shutdown the dispatcher right after the the new coroutine is launched and when the dispatcher is shutdown but there are still active coroutines there it would execute in the "DefaultExecutor". You should move the join up one line.
Most helpful comment
Here is what is going on.
newSingleThreadContext(...).use { ... }would shutdown the dispatcher right after the the new coroutine is launched and when the dispatcher is shutdown but there are still active coroutines there it would execute in the "DefaultExecutor". You should move thejoinup one line.