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 | /** |
| 32 | * Completes the execution of [tryResume] on its non-null result. |
| 33 | */ |
| 34 | fun completeResume(token: Any) |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 35 | |
| 36 | /** |
| 37 | * Makes this continuation cancellable. Use it with `holdCancellability` optional parameter to |
| 38 | * [suspendCancellableCoroutine] function. It throws [IllegalStateException] if invoked more than once. |
| 39 | */ |
| 40 | fun initCancellability() |
Roman Elizarov | 834af46 | 2017-01-23 20:50:29 +0300 | [diff] [blame] | 41 | } |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 42 | |
| 43 | /** |
| 44 | * Suspend coroutine similar to [suspendCoroutine], but provide an implementation of [CancellableContinuation] to |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 45 | * 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] | 46 | * |
| 47 | * If [holdCancellability] optional parameter is `true`, then the coroutine is suspended, but it is not |
| 48 | * cancellable until [CancellableContinuation.initCancellability] is invoked. |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 49 | */ |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 50 | public inline suspend fun <T> suspendCancellableCoroutine( |
| 51 | holdCancellability: Boolean = false, |
| 52 | crossinline block: (CancellableContinuation<T>) -> Unit |
| 53 | ): T = |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 54 | suspendCoroutineOrReturn { cont -> |
| 55 | val safe = SafeCancellableContinuation(cont, getParentJobOrAbort(cont)) |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 56 | if (!holdCancellability) safe.initCancellability() |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 57 | block(safe) |
| 58 | safe.getResult() |
| 59 | } |
| 60 | |
| 61 | // --------------- implementation details --------------- |
| 62 | |
| 63 | @PublishedApi |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 64 | internal fun getParentJobOrAbort(cont: Continuation<*>): Job? { |
| 65 | val job = cont.context[Job] |
| 66 | // 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] | 67 | if (job != null && !job.isActive) throw job.getInactiveCancellationException() |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 68 | return job |
| 69 | } |
| 70 | |
| 71 | @PublishedApi |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 72 | internal class SafeCancellableContinuation<in T>( |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 73 | private val delegate: Continuation<T>, |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 74 | private val parentJob: Job? |
Roman Elizarov | 53a0a40 | 2017-01-19 20:21:57 +0300 | [diff] [blame] | 75 | ) : AbstractCoroutine<T>(delegate.context), CancellableContinuation<T> { |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 76 | // only updated from the thread that invoked suspendCancellableCoroutine |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 77 | |
| 78 | @Volatile |
| 79 | private var decision = UNDECIDED |
| 80 | |
| 81 | private companion object { |
| 82 | val DECISION: AtomicIntegerFieldUpdater<SafeCancellableContinuation<*>> = |
| 83 | AtomicIntegerFieldUpdater.newUpdater(SafeCancellableContinuation::class.java, "decision") |
| 84 | |
| 85 | const val UNDECIDED = 0 |
| 86 | const val SUSPENDED = 1 |
| 87 | const val RESUMED = 2 |
| 88 | const val YIELD = 3 // used by cancellable "yield" |
| 89 | } |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 90 | |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 91 | override fun initCancellability() { |
| 92 | initParentJob(parentJob) |
| 93 | } |
Roman Elizarov | 58a7add | 2017-01-20 12:19:52 +0300 | [diff] [blame] | 94 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 95 | fun getResult(): Any? { |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 96 | val decision = this.decision // volatile read |
| 97 | when (decision) { |
Roman Elizarov | ea4a51b | 2017-01-31 12:01:25 +0300 | [diff] [blame] | 98 | UNDECIDED -> if (DECISION.compareAndSet(this, UNDECIDED, SUSPENDED)) return COROUTINE_SUSPENDED |
| 99 | YIELD -> return COROUTINE_SUSPENDED |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 100 | } |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 101 | // otherwise, afterCompletion was already invoked, and the result is in the state |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 102 | val state = getState() |
| 103 | if (state is CompletedExceptionally) throw state.exception |
| 104 | return state |
| 105 | } |
| 106 | |
Roman Elizarov | 834af46 | 2017-01-23 20:50:29 +0300 | [diff] [blame] | 107 | override val isCancelled: Boolean |
| 108 | get() = getState() is Cancelled |
| 109 | |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame^] | 110 | override fun tryResume(value: T): Any? { |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 111 | while (true) { // lock-free loop on state |
| 112 | val state = getState() // atomic read |
| 113 | when (state) { |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame^] | 114 | is Active -> if (tryUpdateState(state, value)) return state |
| 115 | else -> return null // cannot resume -- not active anymore |
Roman Elizarov | 187eace | 2017-01-31 09:39:58 +0300 | [diff] [blame] | 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
Roman Elizarov | 7b2d8b0 | 2017-02-02 20:09:14 +0300 | [diff] [blame^] | 120 | override fun completeResume(token: Any) { |
| 121 | completeUpdateState(token, getState()) |
| 122 | } |
| 123 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 124 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | 53a0a40 | 2017-01-19 20:21:57 +0300 | [diff] [blame] | 125 | override fun afterCompletion(state: Any?) { |
Roman Elizarov | 7cf452e | 2017-01-29 21:58:33 +0300 | [diff] [blame] | 126 | val decision = this.decision // volatile read |
| 127 | if (decision == UNDECIDED && DECISION.compareAndSet(this, UNDECIDED, RESUMED)) return // will get result in getResult |
| 128 | // otherwise, getResult has already commenced, i.e. it was resumed later or in other thread |
| 129 | if (state is CompletedExceptionally) |
| 130 | delegate.resumeWithException(state.exception) |
| 131 | else if (decision == YIELD && delegate is DispatchedContinuation) |
| 132 | delegate.resumeYield(parentJob, state as T) |
| 133 | else |
| 134 | delegate.resume(state as T) |
| 135 | } |
| 136 | |
| 137 | // can only be invoked in the same thread as getResult (see "yield"), afterCompletion may be concurrent |
| 138 | fun resumeYield(value: T) { |
| 139 | if ((context[ContinuationInterceptor] as? CoroutineDispatcher)?.isDispatchNeeded(context) == true) |
| 140 | DECISION.compareAndSet(this, UNDECIDED, YIELD) // try mark as needing dispatch |
| 141 | resume(value) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 142 | } |
| 143 | } |