-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Introduce CoroutineDispatcher.limitedParallelism #2918
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
f0a265a
Introduce CoroutineDispatcher.limitedParallelism
qwwdfsad 00122c5
Handle unexpected exceptions in the dispatcher when throwing runnable…
qwwdfsad ecd36dd
LimitedDispatcher fixes
qwwdfsad 5fe0261
Elastic Dispatchers.IO
qwwdfsad 4b752fe
Reduce number of internal classes
qwwdfsad ee27e2b
~limited parallelism improvements: better docs and tests
qwwdfsad eafefb4
~tweak contract for limitedParallelism on direct dispatchers, prohibi…
qwwdfsad 274cdb4
~structurred concurrency in TaskTest to avoid failures related to clo…
qwwdfsad ce0f3dd
~replace ISE with UnsupportedOperationException
qwwdfsad File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
105 changes: 105 additions & 0 deletions
105
kotlinx-coroutines-core/common/src/internal/LimitedDispatcher.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
/* | ||
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package kotlinx.coroutines.internal | ||
|
||
import kotlinx.coroutines.* | ||
import kotlin.coroutines.* | ||
import kotlin.jvm.* | ||
|
||
/** | ||
* The result of .limitedParallelism(x) call, a dispatcher | ||
* that wraps the given dispatcher, but limits the parallelism level, while | ||
* trying to emulate fairness. | ||
*/ | ||
internal class LimitedDispatcher( | ||
private val dispatcher: CoroutineDispatcher, | ||
private val parallelism: Int | ||
) : CoroutineDispatcher(), Runnable, Delay by (dispatcher as? Delay ?: DefaultDelay) { | ||
qwwdfsad marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
@Volatile | ||
private var runningWorkers = 0 | ||
|
||
private val queue = LockFreeTaskQueue<Runnable>(singleConsumer = false) | ||
|
||
@ExperimentalCoroutinesApi | ||
override fun limitedParallelism(parallelism: Int): CoroutineDispatcher { | ||
parallelism.checkParallelism() | ||
if (parallelism >= this.parallelism) return this | ||
return super.limitedParallelism(parallelism) | ||
} | ||
|
||
override fun run() { | ||
var fairnessCounter = 0 | ||
while (true) { | ||
val task = queue.removeFirstOrNull() | ||
if (task != null) { | ||
try { | ||
task.run() | ||
} catch (e: Throwable) { | ||
handleCoroutineException(EmptyCoroutineContext, e) | ||
} | ||
// 16 is our out-of-thin-air constant to emulate fairness. Used in JS dispatchers as well | ||
if (++fairnessCounter >= 16 && dispatcher.isDispatchNeeded(this)) { | ||
// Do "yield" to let other views to execute their runnable as well | ||
// Note that we do not decrement 'runningWorkers' as we still committed to do our part of work | ||
dispatcher.dispatch(this, this) | ||
return | ||
} | ||
continue | ||
} | ||
|
||
@Suppress("CAST_NEVER_SUCCEEDS") | ||
synchronized(this as SynchronizedObject) { | ||
--runningWorkers | ||
if (queue.size == 0) return | ||
++runningWorkers | ||
fairnessCounter = 0 | ||
} | ||
} | ||
} | ||
|
||
override fun dispatch(context: CoroutineContext, block: Runnable) { | ||
dispatchInternal(block) { | ||
dispatcher.dispatch(this, this) | ||
} | ||
} | ||
|
||
@InternalCoroutinesApi | ||
override fun dispatchYield(context: CoroutineContext, block: Runnable) { | ||
dispatchInternal(block) { | ||
dispatcher.dispatchYield(this, this) | ||
} | ||
} | ||
|
||
private inline fun dispatchInternal(block: Runnable, dispatch: () -> Unit) { | ||
// Add task to queue so running workers will be able to see that | ||
if (addAndTryDispatching(block)) return | ||
/* | ||
* Protect against the race when the number of workers is enough, | ||
* but one (because of synchronized serialization) attempts to complete, | ||
* and we just observed the number of running workers smaller than the actual | ||
* number (hit right between `--runningWorkers` and `++runningWorkers` in `run()`) | ||
*/ | ||
if (!tryAllocateWorker()) return | ||
dispatch() | ||
} | ||
|
||
private fun tryAllocateWorker(): Boolean { | ||
@Suppress("CAST_NEVER_SUCCEEDS") | ||
synchronized(this as SynchronizedObject) { | ||
if (runningWorkers >= parallelism) return false | ||
++runningWorkers | ||
return true | ||
} | ||
} | ||
|
||
private fun addAndTryDispatching(block: Runnable): Boolean { | ||
queue.addLast(block) | ||
return runningWorkers >= parallelism | ||
} | ||
} | ||
|
||
// Save a few bytecode ops | ||
internal fun Int.checkParallelism() = require(this >= 1) { "Expected positive parallelism level, but got $this" } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The IDE highlight
EXPERIMENTAL
as being never used. Can't this line be removed altogether?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IDE is wrong here, JMH's
@Param
applied to enum enumerates all enum values in the benchmark