Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016-2017 JetBrains s.r.o. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 17 | package kotlinx.coroutines.experimental |
| 18 | |
Roman Elizarov | 4638d79 | 2017-03-14 19:39:26 +0300 | [diff] [blame] | 19 | import kotlinx.coroutines.experimental.intrinsics.startCoroutineUndispatched |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 20 | import kotlinx.coroutines.experimental.selects.SelectBuilder |
| 21 | import kotlinx.coroutines.experimental.selects.SelectInstance |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 22 | import kotlinx.coroutines.experimental.selects.select |
Roman Elizarov | ea4a51b | 2017-01-31 12:01:25 +0300 | [diff] [blame] | 23 | import kotlin.coroutines.experimental.CoroutineContext |
| 24 | import kotlin.coroutines.experimental.startCoroutine |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 25 | |
| 26 | /** |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 27 | * Deferred value is a non-blocking cancellable future. |
| 28 | * It is created with [async] coroutine builder. |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 29 | * It is in [active][isActive] state while the value is being computed. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 30 | * |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 31 | * Deferred value has four or five possible states. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 32 | * |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 33 | * | **State** | [isActive] | [isCompleted] | [isCompletedExceptionally] | [isCancelled] | |
Roman Elizarov | 7886ef6 | 2017-02-13 14:00:18 +0300 | [diff] [blame] | 34 | * | -------------------------------- | ---------- | ------------- | -------------------------- | ------------- | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 35 | * | _New_ (optional initial state) | `false` | `false` | `false` | `false` | |
| 36 | * | _Active_ (default initial state) | `true` | `false` | `false` | `false` | |
| 37 | * | _Resolved_ (final state) | `false` | `true` | `false` | `false` | |
| 38 | * | _Failed_ (final state) | `false` | `true` | `true` | `false` | |
| 39 | * | _Cancelled_ (final state) | `false` | `true` | `true` | `true` | |
| 40 | * |
| 41 | * Usually, a deferred value is created in _active_ state (it is created and started), so its only visible |
| 42 | * states are _active_ and _completed_ (_resolved_, _failed_, or _cancelled_) state. |
| 43 | * However, [async] coroutine builder has an optional `start` parameter that creates a deferred value in _new_ state |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 44 | * when this parameter is set to [CoroutineStart.LAZY]. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 45 | * Such a deferred can be be made _active_ by invoking [start], [join], or [await]. |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 46 | */ |
| 47 | public interface Deferred<out T> : Job { |
| 48 | /** |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 49 | * Returns `true` if computation of this deferred value has _completed exceptionally_ -- it had |
| 50 | * either _failed_ with exception during computation or was [cancelled][cancel]. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 51 | * |
| 52 | * It implies that [isActive] is `false` and [isCompleted] is `true`. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 53 | */ |
| 54 | val isCompletedExceptionally: Boolean |
| 55 | |
| 56 | /** |
| 57 | * Returns `true` if computation of this deferred value was [cancelled][cancel]. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 58 | * |
| 59 | * It implies that [isActive] is `false`, [isCompleted] is `true`, and [isCompletedExceptionally] is `true`. |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 60 | */ |
| 61 | val isCancelled: Boolean |
| 62 | |
| 63 | /** |
Roman Elizarov | be4cae3 | 2017-02-15 17:57:02 +0300 | [diff] [blame] | 64 | * Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete, |
| 65 | * returning the resulting value or throwing the corresponding exception if the deferred had completed exceptionally. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 66 | * |
Roman Elizarov | be4cae3 | 2017-02-15 17:57:02 +0300 | [diff] [blame] | 67 | * This suspending function is cancellable. |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 68 | * If the [Job] of the current coroutine is completed while this suspending function is waiting, this function |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 69 | * immediately resumes with [CancellationException]. |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 70 | * |
| 71 | * This function can be used in [select] invocation with [onAwait][SelectBuilder.onAwait] clause. |
| 72 | * Use [isCompleted] to check for completion of this deferred value without waiting. |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 73 | */ |
| 74 | public suspend fun await(): T |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 75 | |
| 76 | /** |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 77 | * Registers [onAwait][SelectBuilder.onAwait] select clause. |
| 78 | * @suppress **This is unstable API and it is subject to change.** |
| 79 | */ |
| 80 | public fun <R> registerSelectAwait(select: SelectInstance<R>, block: suspend (T) -> R) |
| 81 | |
| 82 | /** |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 83 | * Returns *completed* result or throws [IllegalStateException] if this deferred value has not |
| 84 | * [completed][isCompleted] yet. It throws the corresponding exception if this deferred has |
| 85 | * [completed exceptionally][isCompletedExceptionally]. |
| 86 | * |
Roman Elizarov | e780347 | 2017-02-16 09:52:31 +0300 | [diff] [blame] | 87 | * This function is designed to be used from [invokeOnCompletion] handlers, when there is an absolute certainty that |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 88 | * the value is already complete. |
| 89 | */ |
| 90 | public fun getCompleted(): T |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 91 | |
| 92 | /** |
Roman Elizarov | fc7a9a2 | 2017-02-13 11:54:01 +0300 | [diff] [blame] | 93 | * @suppress **Deprecated**: Use `isActive`. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 94 | */ |
| 95 | @Deprecated(message = "Use `isActive`", replaceWith = ReplaceWith("isActive")) |
| 96 | public val isComputing: Boolean get() = isActive |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 97 | } |
| 98 | |
| 99 | /** |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 100 | * Creates new coroutine and returns its future result as an implementation of [Deferred]. |
Roman Elizarov | 44ba4b1 | 2017-01-25 11:37:54 +0300 | [diff] [blame] | 101 | * |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 102 | * The running coroutine is cancelled when the resulting object is [cancelled][Job.cancel]. |
Roman Elizarov | 44ba4b1 | 2017-01-25 11:37:54 +0300 | [diff] [blame] | 103 | * The [context] for the new coroutine must be explicitly specified. |
Roman Elizarov | ed7b864 | 2017-01-19 11:22:28 +0300 | [diff] [blame] | 104 | * See [CoroutineDispatcher] for the standard [context] implementations that are provided by `kotlinx.coroutines`. |
Roman Elizarov | 44ba4b1 | 2017-01-25 11:37:54 +0300 | [diff] [blame] | 105 | * The [context][CoroutineScope.context] of the parent coroutine from its [scope][CoroutineScope] may be used, |
| 106 | * in which case the [Job] of the resulting coroutine is a child of the job of the parent coroutine. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 107 | * |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 108 | * By default, the coroutine is immediately started. |
| 109 | * An optional [start] parameter can be set to [CoroutineStart.LAZY] to start coroutine _lazily_. In this case,, |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 110 | * the resulting [Deferred] is created in _new_ state. It can be explicitly started with [start][Job.start] |
| 111 | * function and will be started implicitly on the first invocation of [join][Job.join] or [await][Deferred.await]. |
| 112 | * |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 113 | * @param context context of the coroutine |
| 114 | * @param start coroutine start option |
| 115 | * @param block the coroutine code |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 116 | */ |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 117 | public fun <T> async( |
| 118 | context: CoroutineContext, |
| 119 | start: CoroutineStart = CoroutineStart.DEFAULT, |
| 120 | block: suspend CoroutineScope.() -> T |
| 121 | ): Deferred<T> { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 122 | val newContext = newCoroutineContext(context) |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 123 | val coroutine = if (start.isLazy) |
| 124 | LazyDeferredCoroutine(newContext, block) else |
| 125 | DeferredCoroutine<T>(newContext, active = true) |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 126 | coroutine.initParentJob(context[Job]) |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 127 | start(block, coroutine, coroutine) |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 128 | return coroutine |
| 129 | } |
| 130 | |
| 131 | /** |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 132 | * @suppress **Deprecated**: Use `start = CoroutineStart.XXX` parameter |
| 133 | */ |
| 134 | @Deprecated(message = "Use `start = CoroutineStart.XXX` parameter", |
| 135 | replaceWith = ReplaceWith("async(context, if (start) CoroutineStart.DEFAULT else CoroutineStart.LAZY, block)")) |
| 136 | public fun <T> async(context: CoroutineContext, start: Boolean, block: suspend CoroutineScope.() -> T): Deferred<T> = |
| 137 | async(context, if (start) CoroutineStart.DEFAULT else CoroutineStart.LAZY, block) |
| 138 | |
| 139 | /** |
Roman Elizarov | fc7a9a2 | 2017-02-13 11:54:01 +0300 | [diff] [blame] | 140 | * @suppress **Deprecated**: `defer` was renamed to `async`. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 141 | */ |
| 142 | @Deprecated(message = "`defer` was renamed to `async`", level = DeprecationLevel.WARNING, |
| 143 | replaceWith = ReplaceWith("async(context, block = block)")) |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 144 | public fun <T> defer(context: CoroutineContext, block: suspend CoroutineScope.() -> T): Deferred<T> = |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 145 | async(context, block = block) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 146 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 147 | private open class DeferredCoroutine<T>( |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 148 | override val parentContext: CoroutineContext, |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 149 | active: Boolean |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 150 | ) : AbstractCoroutine<T>(active), Deferred<T> { |
Roman Elizarov | ee7c0eb | 2017-02-16 15:29:28 +0300 | [diff] [blame] | 151 | override val isCompletedExceptionally: Boolean get() = state is CompletedExceptionally |
| 152 | override val isCancelled: Boolean get() = state is Cancelled |
Roman Elizarov | b7c46de | 2017-02-08 12:35:24 +0300 | [diff] [blame] | 153 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 154 | @Suppress("UNCHECKED_CAST") |
| 155 | suspend override fun await(): T { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 156 | // fast-path -- check state (avoid extra object creation) |
| 157 | while(true) { // lock-free loop on state |
Roman Elizarov | ee7c0eb | 2017-02-16 15:29:28 +0300 | [diff] [blame] | 158 | val state = this.state |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 159 | if (state !is Incomplete) { |
| 160 | // already complete -- just return result |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 161 | if (state is CompletedExceptionally) throw state.exception |
| 162 | return state as T |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 163 | |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 164 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 165 | if (startInternal(state) >= 0) break // break unless needs to retry |
Roman Elizarov | 41c5c8b | 2017-01-25 13:37:15 +0300 | [diff] [blame] | 166 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 167 | return awaitSuspend() // slow-path |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 168 | } |
| 169 | |
| 170 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 171 | private suspend fun awaitSuspend(): T = suspendCancellableCoroutine { cont -> |
Roman Elizarov | daa1d9d | 2017-03-02 19:00:50 +0300 | [diff] [blame] | 172 | cont.disposeOnCompletion(invokeOnCompletion { |
Roman Elizarov | ee7c0eb | 2017-02-16 15:29:28 +0300 | [diff] [blame] | 173 | val state = this.state |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 174 | check(state !is Incomplete) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 175 | if (state is CompletedExceptionally) |
| 176 | cont.resumeWithException(state.exception) |
| 177 | else |
| 178 | cont.resume(state as T) |
| 179 | }) |
| 180 | } |
| 181 | |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 182 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 183 | override fun <R> registerSelectAwait(select: SelectInstance<R>, block: suspend (T) -> R) { |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 184 | // fast-path -- check state and select/return if needed |
| 185 | while (true) { |
| 186 | if (select.isSelected) return |
| 187 | val state = this.state |
| 188 | if (state !is Incomplete) { |
| 189 | // already complete -- select result |
| 190 | if (select.trySelect(idempotent = null)) { |
| 191 | if (state is CompletedExceptionally) |
| 192 | select.resumeSelectWithException(state.exception, MODE_DIRECT) |
| 193 | else |
Roman Elizarov | 4638d79 | 2017-03-14 19:39:26 +0300 | [diff] [blame] | 194 | block.startCoroutineUndispatched(state as T, select.completion) |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 195 | } |
| 196 | return |
| 197 | } |
| 198 | if (startInternal(state) == 0) { |
| 199 | // slow-path -- register waiter for completion |
Roman Elizarov | daa1d9d | 2017-03-02 19:00:50 +0300 | [diff] [blame] | 200 | select.disposeOnSelect(invokeOnCompletion(SelectAwaitOnCompletion(this, select, block))) |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 201 | return |
| 202 | } |
| 203 | } |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 204 | } |
| 205 | |
| 206 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 207 | internal fun <R> selectAwaitCompletion(select: SelectInstance<R>, block: suspend (T) -> R, state: Any? = this.state) { |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 208 | if (select.trySelect(idempotent = null)) { |
| 209 | if (state is CompletedExceptionally) |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 210 | select.resumeSelectWithException(state.exception, MODE_DISPATCHED) |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 211 | else |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 212 | block.startCoroutine(state as T, select.completion) |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 213 | } |
| 214 | } |
| 215 | |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 216 | @Suppress("UNCHECKED_CAST") |
| 217 | override fun getCompleted(): T { |
Roman Elizarov | ee7c0eb | 2017-02-16 15:29:28 +0300 | [diff] [blame] | 218 | val state = this.state |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 219 | check(state !is Incomplete) { "This deferred value has not completed yet" } |
Roman Elizarov | c581454 | 2017-01-19 10:19:06 +0300 | [diff] [blame] | 220 | if (state is CompletedExceptionally) throw state.exception |
| 221 | return state as T |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 222 | } |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 223 | } |
| 224 | |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 225 | private class SelectAwaitOnCompletion<T, R>( |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 226 | deferred: DeferredCoroutine<T>, |
| 227 | private val select: SelectInstance<R>, |
| 228 | private val block: suspend (T) -> R |
| 229 | ) : JobNode<DeferredCoroutine<T>>(deferred) { |
Roman Elizarov | d84dbc2 | 2017-02-22 14:56:58 +0300 | [diff] [blame] | 230 | override fun invoke(reason: Throwable?) = job.selectAwaitCompletion(select, block) |
| 231 | override fun toString(): String = "SelectAwaitOnCompletion[$select]" |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 232 | } |
| 233 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 234 | private class LazyDeferredCoroutine<T>( |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame] | 235 | parentContext: CoroutineContext, |
| 236 | private val block: suspend CoroutineScope.() -> T |
| 237 | ) : DeferredCoroutine<T>(parentContext, active = false) { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 238 | override fun onStart() { |
| 239 | block.startCoroutine(this, this) |
| 240 | } |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 241 | } |