|
| 1 | +/* |
| 2 | + * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | + |
| 5 | +package kotlinx.coroutines.internal |
| 6 | + |
| 7 | +import kotlinx.coroutines.* |
| 8 | +import kotlin.coroutines.* |
| 9 | +import kotlin.jvm.* |
| 10 | + |
| 11 | +/** |
| 12 | + * The result of .limitedParallelism(x) call, a dispatcher |
| 13 | + * that wraps the given dispatcher, but limits the parallelism level, while |
| 14 | + * trying to emulate fairness. |
| 15 | + */ |
| 16 | +internal class LimitedDispatcher( |
| 17 | + private val dispatcher: CoroutineDispatcher, |
| 18 | + private val parallelism: Int |
| 19 | +) : CoroutineDispatcher(), Runnable, Delay by (dispatcher as? Delay ?: DefaultDelay) { |
| 20 | + |
| 21 | + @Volatile |
| 22 | + private var runningWorkers = 0 |
| 23 | + |
| 24 | + private val queue = LockFreeTaskQueue<Runnable>(singleConsumer = false) |
| 25 | + |
| 26 | + @ExperimentalCoroutinesApi |
| 27 | + override fun limitedParallelism(parallelism: Int): CoroutineDispatcher { |
| 28 | + parallelism.checkParallelism() |
| 29 | + if (parallelism >= this.parallelism) return this |
| 30 | + return super.limitedParallelism(parallelism) |
| 31 | + } |
| 32 | + |
| 33 | + override fun run() { |
| 34 | + var fairnessCounter = 0 |
| 35 | + while (true) { |
| 36 | + val task = queue.removeFirstOrNull() |
| 37 | + if (task != null) { |
| 38 | + try { |
| 39 | + task.run() |
| 40 | + } catch (e: Throwable) { |
| 41 | + handleCoroutineException(EmptyCoroutineContext, e) |
| 42 | + } |
| 43 | + // 16 is our out-of-thin-air constant to emulate fairness. Used in JS dispatchers as well |
| 44 | + if (++fairnessCounter >= 16 && dispatcher.isDispatchNeeded(this)) { |
| 45 | + // Do "yield" to let other views to execute their runnable as well |
| 46 | + // Note that we do not decrement 'runningWorkers' as we still committed to do our part of work |
| 47 | + dispatcher.dispatch(this, this) |
| 48 | + return |
| 49 | + } |
| 50 | + continue |
| 51 | + } |
| 52 | + |
| 53 | + @Suppress("CAST_NEVER_SUCCEEDS") |
| 54 | + synchronized(this as SynchronizedObject) { |
| 55 | + --runningWorkers |
| 56 | + if (queue.size == 0) return |
| 57 | + ++runningWorkers |
| 58 | + fairnessCounter = 0 |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + override fun dispatch(context: CoroutineContext, block: Runnable) { |
| 64 | + dispatchInternal(block) { |
| 65 | + dispatcher.dispatch(this, this) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + @InternalCoroutinesApi |
| 70 | + override fun dispatchYield(context: CoroutineContext, block: Runnable) { |
| 71 | + dispatchInternal(block) { |
| 72 | + dispatcher.dispatchYield(this, this) |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + private inline fun dispatchInternal(block: Runnable, dispatch: () -> Unit) { |
| 77 | + // Add task to queue so running workers will be able to see that |
| 78 | + if (addAndTryDispatching(block)) return |
| 79 | + /* |
| 80 | + * Protect against the race when the number of workers is enough, |
| 81 | + * but one (because of synchronized serialization) attempts to complete, |
| 82 | + * and we just observed the number of running workers smaller than the actual |
| 83 | + * number (hit right between `--runningWorkers` and `++runningWorkers` in `run()`) |
| 84 | + */ |
| 85 | + if (!tryAllocateWorker()) return |
| 86 | + dispatch() |
| 87 | + } |
| 88 | + |
| 89 | + private fun tryAllocateWorker(): Boolean { |
| 90 | + @Suppress("CAST_NEVER_SUCCEEDS") |
| 91 | + synchronized(this as SynchronizedObject) { |
| 92 | + if (runningWorkers >= parallelism) return false |
| 93 | + ++runningWorkers |
| 94 | + return true |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + private fun addAndTryDispatching(block: Runnable): Boolean { |
| 99 | + queue.addLast(block) |
| 100 | + return runningWorkers >= parallelism |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +// Save a few bytecode ops |
| 105 | +internal fun Int.checkParallelism() = require(this >= 1) { "Expected positive parallelism level, but got $this" } |
0 commit comments