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