Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CoroutineDispatcher.asExecutor() to respect isDispatchNeeded #3683

Merged
merged 1 commit into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}
}
}