Skip to content

Commit

Permalink
CoroutineDispatcher.asExecutor() to respect isDispatchNeeded (#3683)
Browse files Browse the repository at this point in the history
Calling `Dispatchers.Main.immediate.asExecutor().execute { ... }`
should respect the fact that it's immediate and avoid dispatch (and
posting to the Looper) when in the right context.
  • Loading branch information
odedniv committed Apr 17, 2023
1 parent 11d7ac0 commit 915347c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
9 changes: 8 additions & 1 deletion kotlinx-coroutines-core/jvm/src/Executors.kt
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,14 @@ public fun CoroutineDispatcher.asExecutor(): Executor =
(this as? ExecutorCoroutineDispatcher)?.executor ?: DispatcherExecutor(this)

private class DispatcherExecutor(@JvmField val dispatcher: CoroutineDispatcher) : Executor {
override fun execute(block: Runnable) = dispatcher.dispatch(EmptyCoroutineContext, block)
override fun execute(block: Runnable) {
if (dispatcher.isDispatchNeeded(EmptyCoroutineContext)) {
dispatcher.dispatch(EmptyCoroutineContext, block)
} else {
block.run()
}
}

override fun toString(): String = dispatcher.toString()
}

Expand Down
18 changes: 17 additions & 1 deletion kotlinx-coroutines-core/jvm/test/ExecutorsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,22 @@ class ExecutorsTest : TestBase() {
finish(4)
}

@Test
fun testCustomDispatcherToExecutorDispatchNotNeeded() {
expect(1)
val dispatcher = object : CoroutineDispatcher() {
override fun isDispatchNeeded(context: CoroutineContext) = false

override fun dispatch(context: CoroutineContext, block: Runnable) {
fail("should not dispatch")
}
}
dispatcher.asExecutor().execute {
expect(2)
}
finish(3)
}

@Test
fun testTwoThreads() {
val ctx1 = newSingleThreadContext("Ctx1")
Expand All @@ -106,4 +122,4 @@ class ExecutorsTest : TestBase() {
dispatcher.close()
check(executorService.isShutdown)
}
}
}

0 comments on commit 915347c

Please sign in to comment.