1 package kotlinx.coroutines 2 3 import kotlinx.coroutines.internal.* 4 import kotlin.coroutines.* 5 6 /** 7 * Base class to be extended by all coroutine dispatcher implementations. 8 * 9 * The following standard implementations are provided by `kotlinx.coroutines` as properties on 10 * the [Dispatchers] object: 11 * 12 * - [Dispatchers.Default] — is used by all standard builders if no dispatcher or any other [ContinuationInterceptor] 13 * is specified in their context. It uses a common pool of shared background threads. 14 * This is an appropriate choice for compute-intensive coroutines that consume CPU resources. 15 * - [Dispatchers.IO] — uses a shared pool of on-demand created threads and is designed for offloading of IO-intensive _blocking_ 16 * operations (like file I/O and blocking socket I/O). 17 * - [Dispatchers.Unconfined] — starts coroutine execution in the current call-frame until the first suspension, 18 * whereupon the coroutine builder function returns. 19 * The coroutine will later resume in whatever thread used by the 20 * corresponding suspending function, without confining it to any specific thread or pool. 21 * **The `Unconfined` dispatcher should not normally be used in code**. 22 * - Private thread pools can be created with [newSingleThreadContext] and [newFixedThreadPoolContext]. 23 * - An arbitrary [Executor][java.util.concurrent.Executor] can be converted to a dispatcher with the [asCoroutineDispatcher] extension function. 24 * 25 * This class ensures that debugging facilities in [newCoroutineContext] function work properly. 26 */ 27 public abstract class CoroutineDispatcher : 28 AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor { 29 30 /** @suppress */ 31 @ExperimentalStdlibApi 32 public companion object Key : AbstractCoroutineContextKey<ContinuationInterceptor, CoroutineDispatcher>( 33 ContinuationInterceptor, <lambda>null34 { it as? CoroutineDispatcher }) 35 36 /** 37 * Returns `true` if the execution of the coroutine should be performed with [dispatch] method. 38 * The default behavior for most dispatchers is to return `true`. 39 * 40 * If this method returns `false`, the coroutine is resumed immediately in the current thread, 41 * potentially forming an event-loop to prevent stack overflows. 42 * The event loop is an advanced topic and its implications can be found in [Dispatchers.Unconfined] documentation. 43 * 44 * The [context] parameter represents the context of the coroutine that is being dispatched, 45 * or [EmptyCoroutineContext] if a non-coroutine-specific [Runnable] is dispatched instead. 46 * 47 * A dispatcher can override this method to provide a performance optimization and avoid paying a cost of an unnecessary dispatch. 48 * E.g. [MainCoroutineDispatcher.immediate] checks whether we are already in the required UI thread in this method and avoids 49 * an additional dispatch when it is not required. 50 * 51 * While this approach can be more efficient, it is not chosen by default to provide a consistent dispatching behaviour 52 * so that users won't observe unexpected and non-consistent order of events by default. 53 * 54 * Coroutine builders like [launch][CoroutineScope.launch] and [async][CoroutineScope.async] accept an optional [CoroutineStart] 55 * parameter that allows one to optionally choose the [undispatched][CoroutineStart.UNDISPATCHED] behavior to start coroutine immediately, 56 * but to be resumed only in the provided dispatcher. 57 * 58 * This method should generally be exception-safe. An exception thrown from this method 59 * may leave the coroutines that use this dispatcher in the inconsistent and hard to debug state. 60 * 61 * @see dispatch 62 * @see Dispatchers.Unconfined 63 */ isDispatchNeedednull64 public open fun isDispatchNeeded(context: CoroutineContext): Boolean = true 65 66 /** 67 * Creates a view of the current dispatcher that limits the parallelism to the given [value][parallelism]. 68 * The resulting view uses the original dispatcher for execution, but with the guarantee that 69 * no more than [parallelism] coroutines are executed at the same time. 70 * 71 * This method does not impose restrictions on the number of views or the total sum of parallelism values, 72 * each view controls its own parallelism independently with the guarantee that the effective parallelism 73 * of all views cannot exceed the actual parallelism of the original dispatcher. 74 * 75 * ### Limitations 76 * 77 * The default implementation of `limitedParallelism` does not support direct dispatchers, 78 * such as executing the given runnable in place during [dispatch] calls. 79 * Any dispatcher that may return `false` from [isDispatchNeeded] is considered direct. 80 * For direct dispatchers, it is recommended to override this method 81 * and provide a domain-specific implementation or to throw an [UnsupportedOperationException]. 82 * 83 * ### Example of usage 84 * ``` 85 * private val backgroundDispatcher = newFixedThreadPoolContext(4, "App Background") 86 * // At most 2 threads will be processing images as it is really slow and CPU-intensive 87 * private val imageProcessingDispatcher = backgroundDispatcher.limitedParallelism(2) 88 * // At most 3 threads will be processing JSON to avoid image processing starvation 89 * private val jsonProcessingDispatcher = backgroundDispatcher.limitedParallelism(3) 90 * // At most 1 thread will be doing IO 91 * private val fileWriterDispatcher = backgroundDispatcher.limitedParallelism(1) 92 * ``` 93 * Note how in this example the application has an executor with 4 threads, but the total sum of all limits 94 * is 6. Still, at most 4 coroutines can be executed simultaneously as each view limits only its own parallelism. 95 * 96 * Note that this example was structured in such a way that it illustrates the parallelism guarantees. 97 * In practice, it is usually better to use [Dispatchers.IO] or [Dispatchers.Default] instead of creating a 98 * `backgroundDispatcher`. It is both possible and advised to call `limitedParallelism` on them. 99 */ 100 @ExperimentalCoroutinesApi 101 public open fun limitedParallelism(parallelism: Int): CoroutineDispatcher { 102 parallelism.checkParallelism() 103 return LimitedDispatcher(this, parallelism) 104 } 105 106 /** 107 * Requests execution of a runnable [block]. 108 * The dispatcher guarantees that [block] will eventually execute, typically by dispatching it to a thread pool, 109 * using a dedicated thread, or just executing the block in place. 110 * The [context] parameter represents the context of the coroutine that is being dispatched, 111 * or [EmptyCoroutineContext] if a non-coroutine-specific [Runnable] is dispatched instead. 112 * Implementations may use [context] for additional context-specific information, 113 * such as priority, whether the dispatched coroutine can be invoked in place, 114 * coroutine name, and additional diagnostic elements. 115 * 116 * This method should guarantee that the given [block] will be eventually invoked, 117 * otherwise the system may reach a deadlock state and never leave it. 118 * The cancellation mechanism is transparent for [CoroutineDispatcher] and is managed by [block] internals. 119 * 120 * This method should generally be exception-safe. An exception thrown from this method 121 * may leave the coroutines that use this dispatcher in an inconsistent and hard-to-debug state. 122 * 123 * This method must not immediately call [block]. Doing so may result in `StackOverflowError` 124 * when `dispatch` is invoked repeatedly, for example when [yield] is called in a loop. 125 * In order to execute a block in place, it is required to return `false` from [isDispatchNeeded] 126 * and delegate the `dispatch` implementation to `Dispatchers.Unconfined.dispatch` in such cases. 127 * To support this, the coroutines machinery ensures in-place execution and forms an event-loop to 128 * avoid unbound recursion. 129 * 130 * @see isDispatchNeeded 131 * @see Dispatchers.Unconfined 132 */ dispatchnull133 public abstract fun dispatch(context: CoroutineContext, block: Runnable) 134 135 /** 136 * Dispatches execution of a runnable `block` onto another thread in the given `context` 137 * with a hint for the dispatcher that the current dispatch is triggered by a [yield] call, so that the execution of this 138 * continuation may be delayed in favor of already dispatched coroutines. 139 * 140 * Though the `yield` marker may be passed as a part of [context], this 141 * is a separate method for performance reasons. 142 * 143 * @suppress **This an internal API and should not be used from general code.** 144 */ 145 @InternalCoroutinesApi 146 public open fun dispatchYield(context: CoroutineContext, block: Runnable): Unit = dispatch(context, block) 147 148 /** 149 * Returns a continuation that wraps the provided [continuation], thus intercepting all resumptions. 150 * 151 * This method should generally be exception-safe. An exception thrown from this method 152 * may leave the coroutines that use this dispatcher in the inconsistent and hard to debug state. 153 */ 154 public final override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = 155 DispatchedContinuation(this, continuation) 156 157 public final override fun releaseInterceptedContinuation(continuation: Continuation<*>) { 158 /* 159 * Unconditional cast is safe here: we only return DispatchedContinuation from `interceptContinuation`, 160 * any ClassCastException can only indicate compiler bug 161 */ 162 val dispatched = continuation as DispatchedContinuation<*> 163 dispatched.release() 164 } 165 166 /** 167 * @suppress **Error**: Operator '+' on two CoroutineDispatcher objects is meaningless. 168 * CoroutineDispatcher is a coroutine context element and `+` is a set-sum operator for coroutine contexts. 169 * The dispatcher to the right of `+` just replaces the dispatcher to the left. 170 */ 171 @Suppress("DeprecatedCallableAddReplaceWith") 172 @Deprecated( 173 message = "Operator '+' on two CoroutineDispatcher objects is meaningless. " + 174 "CoroutineDispatcher is a coroutine context element and `+` is a set-sum operator for coroutine contexts. " + 175 "The dispatcher to the right of `+` just replaces the dispatcher to the left.", 176 level = DeprecationLevel.ERROR 177 ) plusnull178 public operator fun plus(other: CoroutineDispatcher): CoroutineDispatcher = other 179 180 /** @suppress for nicer debugging */ 181 override fun toString(): String = "$classSimpleName@$hexAddress" 182 } 183 184