Skip to content

Commit b74e039

Browse files
authored
Eliminate unneeded LimitedDispatcher instances on Dispatchers.Default and Dispatchers.IO (#3562)
* Handle `Dispatchers.IO.limitedParallelism(Int.MAX_VALUE)` case `LimitedDispatcher.limitedParallelism` returns `this` if requested parallelism is greater or equal to the own parallelism of the said `LimitedDispatcher`. `UnlimitedIoScheduler` has parallelism effectively set to `Int.MAX_VALUE`, so `parallelism >= this.parallelism` check folds into `parallelism == Int.MAX_VALUE`. Before the change `LimitedDispatcher(Int.MAX_VALUE)` was returned. While it does work as expected, any submitted task goes through its queue and `Int.MAX_VALUE` number of workers. The change allows eliminating the `LimitedDispatcher` instance and its queue in this extreme case. * Handle `Dispatchers.Default.limitedParallelism` when requested parallelism >= core pool size (#3442) `LimitedDispatcher.limitedParallelism` returns `this` if requested parallelism is greater or equal to the own parallelism of the said `LimitedDispatcher`. `DefaultScheduler` has parallelism effectively set to `CORE_POOL_SIZE`. Before the change `LimitedDispatcher(parallelism)` was returned. While it does work as expected, any submitted task goes through its queue and `parallelism` number of workers. The change allows eliminating the `LimitedDispatcher` instance and its queue in case the requested parallelism is greater or equal to `CORE_POOL_SIZE`. Fixes #3442
1 parent f4c5725 commit b74e039

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

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

+15
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ internal object DefaultScheduler : SchedulerCoroutineDispatcher(
1414
CORE_POOL_SIZE, MAX_POOL_SIZE,
1515
IDLE_WORKER_KEEP_ALIVE_NS, DEFAULT_SCHEDULER_NAME
1616
) {
17+
18+
@ExperimentalCoroutinesApi
19+
override fun limitedParallelism(parallelism: Int): CoroutineDispatcher {
20+
parallelism.checkParallelism()
21+
if (parallelism >= CORE_POOL_SIZE) return this
22+
return super.limitedParallelism(parallelism)
23+
}
24+
1725
// Shuts down the dispatcher, used only by Dispatchers.shutdown()
1826
internal fun shutdown() {
1927
super.close()
@@ -38,6 +46,13 @@ private object UnlimitedIoScheduler : CoroutineDispatcher() {
3846
override fun dispatch(context: CoroutineContext, block: Runnable) {
3947
DefaultScheduler.dispatchWithContext(block, BlockingContext, false)
4048
}
49+
50+
@ExperimentalCoroutinesApi
51+
override fun limitedParallelism(parallelism: Int): CoroutineDispatcher {
52+
parallelism.checkParallelism()
53+
if (parallelism >= MAX_POOL_SIZE) return this
54+
return super.limitedParallelism(parallelism)
55+
}
4156
}
4257

4358
// Dispatchers.IO

0 commit comments

Comments
 (0)