Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 1 | package kotlinx.coroutines.experimental |
| 2 | |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 3 | import java.util.concurrent.atomic.AtomicIntegerFieldUpdater |
Roman Elizarov | ea4a51b | 2017-01-31 12:01:25 +0300 | [diff] [blame] | 4 | import kotlin.coroutines.experimental.Continuation |
| 5 | import kotlin.coroutines.experimental.ContinuationInterceptor |
| 6 | import kotlin.coroutines.experimental.intrinsics.COROUTINE_SUSPENDED |
| 7 | import kotlin.coroutines.experimental.intrinsics.suspendCoroutineOrReturn |
| 8 | import kotlin.coroutines.experimental.suspendCoroutine |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 9 | |
| 10 | // --------------- cancellable continuations --------------- |
| 11 | |
| 12 | /** |
| 13 | * Cancellable continuation. Its job is completed when it is resumed or cancelled. |
| 14 | * When [cancel] function is explicitly invoked, this continuation resumes with [CancellationException]. |
| 15 | * If the cancel reason was not a [CancellationException], then the original exception is added as cause of the |
| 16 | * [CancellationException] that this continuation resumes with. |
| 17 | */ |
Roman Elizarov | 834af46 | 2017-01-23 20:50:29 +0300 | [diff] [blame] | 18 | public interface CancellableContinuation<in T> : Continuation<T>, Job { |
| 19 | /** |
| 20 | * Returns `true` if this continuation was cancelled. It implies that [isActive] is `false`. |
| 21 | */ |
| 22 | val isCancelled: Boolean |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 23 | |
| 24 | /** |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame] | 25 | * Tries to resume this continuation with a given value and returns non-null object token if it was successful, |
| 26 | * or `null` otherwise (it was already resumed or cancelled). When non-null object was returned, |
| 27 | * [completeResume] must be invoked with it. |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 28 | */ |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame] | 29 | fun tryResume(value: T): Any? |
| 30 | |
| 31 | /** |
Roman Elizarov | f6fed2a | 2017-02-03 19:12:09 +0300 | [diff] [blame^] | 32 | * Tries to resume this continuation with a given exception and returns non-null object token if it was successful, |
| 33 | * or `null` otherwise (it was already resumed or cancelled). When non-null object was returned, |
| 34 | * [completeResume] must be invoked with it. |
| 35 | */ |
| 36 | fun tryResumeWithException(exception: Throwable): Any? |
| 37 | |
| 38 | /** |
| 39 | * Completes the execution of [tryResume] or [tryResumeWithException] on its non-null result. |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame] | 40 | */ |
| 41 | fun completeResume(token: Any) |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 42 | |
| 43 | /** |
| 44 | * Makes this continuation cancellable. Use it with `holdCancellability` optional parameter to |
| 45 | * [suspendCancellableCoroutine] function. It throws [IllegalStateException] if invoked more than once. |
| 46 | */ |
| 47 | fun initCancellability() |
Roman Elizarov | 834af46 | 2017-01-23 20:50:29 +0300 | [diff] [blame] | 48 | } |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 49 | |
| 50 | /** |
| 51 | * Suspend coroutine similar to [suspendCoroutine], but provide an implementation of [CancellableContinuation] to |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 52 | * the [block]. This function throws [CancellationException] if the coroutine is cancelled while suspended. |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 53 | * |
| 54 | * If [holdCancellability] optional parameter is `true`, then the coroutine is suspended, but it is not |
| 55 | * cancellable until [CancellableContinuation.initCancellability] is invoked. |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 56 | */ |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 57 | public inline suspend fun <T> suspendCancellableCoroutine( |
| 58 | holdCancellability: Boolean = false, |
| 59 | crossinline block: (CancellableContinuation<T>) -> Unit |
| 60 | ): T = |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 61 | suspendCoroutineOrReturn { cont -> |
| 62 | val safe = SafeCancellableContinuation(cont, getParentJobOrAbort(cont)) |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 63 | if (!holdCancellability) safe.initCancellability() |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 64 | block(safe) |
| 65 | safe.getResult() |
| 66 | } |
| 67 | |
| 68 | // --------------- implementation details --------------- |
| 69 | |
| 70 | @PublishedApi |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 71 | internal fun getParentJobOrAbort(cont: Continuation<*>): Job? { |
| 72 | val job = cont.context[Job] |
| 73 | // fast path when parent job is already complete (we don't even construct SafeCancellableContinuation object) |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 74 | if (job != null && !job.isActive) throw job.getInactiveCancellationException() |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 75 | return job |
| 76 | } |
| 77 | |
| 78 | @PublishedApi |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 79 | internal class SafeCancellableContinuation<in T>( |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 80 | private val delegate: Continuation<T>, |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 81 | private val parentJob: Job? |
Roman Elizarov | 53a0a40 | 2017-01-19 20:21:57 +0300 | [diff] [blame] | 82 | ) : AbstractCoroutine<T>(delegate.context), CancellableContinuation<T> { |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 83 | // only updated from the thread that invoked suspendCancellableCoroutine |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 84 | |
| 85 | @Volatile |
| 86 | private var decision = UNDECIDED |
| 87 | |
| 88 | private companion object { |
| 89 | val DECISION: AtomicIntegerFieldUpdater<SafeCancellableContinuation<*>> = |
| 90 | AtomicIntegerFieldUpdater.newUpdater(SafeCancellableContinuation::class.java, "decision") |
| 91 | |
| 92 | const val UNDECIDED = 0 |
| 93 | const val SUSPENDED = 1 |
| 94 | const val RESUMED = 2 |
| 95 | const val YIELD = 3 // used by cancellable "yield" |
| 96 | } |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 97 | |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 98 | override fun initCancellability() { |
| 99 | initParentJob(parentJob) |
| 100 | } |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 101 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 102 | fun getResult(): Any? { |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 103 | val decision = this.decision // volatile read |
| 104 | when (decision) { |
Roman Elizarov | ea4a51b | 2017-01-31 12:01:25 +0300 | [diff] [blame] | 105 | UNDECIDED -> if (DECISION.compareAndSet(this, UNDECIDED, SUSPENDED)) return COROUTINE_SUSPENDED |
| 106 | YIELD -> return COROUTINE_SUSPENDED |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 107 | } |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 108 | // otherwise, afterCompletion was already invoked, and the result is in the state |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 109 | val state = getState() |
| 110 | if (state is CompletedExceptionally) throw state.exception |
| 111 | return state |
| 112 | } |
| 113 | |
Roman Elizarov | 834af46 | 2017-01-23 20:50:29 +0300 | [diff] [blame] | 114 | override val isCancelled: Boolean |
| 115 | get() = getState() is Cancelled |
| 116 | |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame] | 117 | override fun tryResume(value: T): Any? { |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 118 | while (true) { // lock-free loop on state |
| 119 | val state = getState() // atomic read |
| 120 | when (state) { |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame] | 121 | is Active -> if (tryUpdateState(state, value)) return state |
| 122 | else -> return null // cannot resume -- not active anymore |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 123 | } |
| 124 | } |
| 125 | } |
| 126 | |
Roman Elizarov | f6fed2a | 2017-02-03 19:12:09 +0300 | [diff] [blame^] | 127 | override fun tryResumeWithException(exception: Throwable): Any? { |
| 128 | while (true) { // lock-free loop on state |
| 129 | val state = getState() // atomic read |
| 130 | when (state) { |
| 131 | is Active -> if (tryUpdateState(state, Failed(exception))) return state |
| 132 | else -> return null // cannot resume -- not active anymore |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame] | 137 | override fun completeResume(token: Any) { |
| 138 | completeUpdateState(token, getState()) |
| 139 | } |
| 140 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 141 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | 53a0a40 | 2017-01-19 20:21:57 +0300 | [diff] [blame] | 142 | override fun afterCompletion(state: Any?) { |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 143 | val decision = this.decision // volatile read |
| 144 | if (decision == UNDECIDED && DECISION.compareAndSet(this, UNDECIDED, RESUMED)) return // will get result in getResult |
| 145 | // otherwise, getResult has already commenced, i.e. it was resumed later or in other thread |
| 146 | if (state is CompletedExceptionally) |
| 147 | delegate.resumeWithException(state.exception) |
| 148 | else if (decision == YIELD && delegate is DispatchedContinuation) |
| 149 | delegate.resumeYield(parentJob, state as T) |
| 150 | else |
| 151 | delegate.resume(state as T) |
| 152 | } |
| 153 | |
| 154 | // can only be invoked in the same thread as getResult (see "yield"), afterCompletion may be concurrent |
| 155 | fun resumeYield(value: T) { |
| 156 | if ((context[ContinuationInterceptor] as? CoroutineDispatcher)?.isDispatchNeeded(context) == true) |
| 157 | DECISION.compareAndSet(this, UNDECIDED, YIELD) // try mark as needing dispatch |
| 158 | resume(value) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 159 | } |
| 160 | } |