Kotlinx.coroutines: `withContext` does not reset context properly

Created on 10 Jul 2018  路  1Comment  路  Source: Kotlin/kotlinx.coroutines

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.

question

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 the join up one line.

>All comments

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.

Was this page helpful?
0 / 5 - 0 ratings