|
| 1 | +/* |
| 2 | + * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | + |
| 5 | +package kotlinx.coroutines |
| 6 | + |
| 7 | +import kotlinx.atomicfu.AtomicRef |
| 8 | +import kotlinx.atomicfu.atomic |
| 9 | +import kotlinx.atomicfu.loop |
| 10 | +import kotlin.coroutines.CoroutineContext |
| 11 | +import kotlin.coroutines.EmptyCoroutineContext |
| 12 | +import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn |
| 13 | + |
| 14 | +/** |
| 15 | + * Makes a blocking code block cancellable (become a cancellation point of the coroutine). |
| 16 | + * |
| 17 | + * The blocking code block will be interrupted and this function will throw [CancellationException] |
| 18 | + * if the coroutine is cancelled. |
| 19 | + * |
| 20 | + * Example: |
| 21 | + * ``` |
| 22 | + * GlobalScope.launch(Dispatchers.IO) { |
| 23 | + * async { |
| 24 | + * // This function will throw [CancellationException]. |
| 25 | + * runInterruptible { |
| 26 | + * doSomethingUseful() |
| 27 | + * |
| 28 | + * // This blocking procedure will be interrupted when this coroutine is canceled |
| 29 | + * // by Exception thrown by the below async block. |
| 30 | + * doSomethingElseUsefulInterruptible() |
| 31 | + * } |
| 32 | + * } |
| 33 | + * |
| 34 | + * async { |
| 35 | + * delay(500L) |
| 36 | + * throw Exception() |
| 37 | + * } |
| 38 | + * } |
| 39 | + * ``` |
| 40 | + * |
| 41 | + * There is also an optional context parameter to this function to enable single-call conversion of |
| 42 | + * interruptible Java methods into main-safe suspending functions like this: |
| 43 | + * ``` |
| 44 | + * // With one call here we are moving the call to Dispatchers.IO and supporting interruption. |
| 45 | + * suspend fun <T> BlockingQueue<T>.awaitTake(): T = |
| 46 | + * runInterruptible(Dispatchers.IO) { queue.take() } |
| 47 | + * ``` |
| 48 | + * |
| 49 | + * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine. |
| 50 | + * @param block regular blocking block that will be interrupted on coroutine cancellation. |
| 51 | + */ |
| 52 | +public suspend fun <T> runInterruptible( |
| 53 | + context: CoroutineContext = EmptyCoroutineContext, |
| 54 | + block: () -> T |
| 55 | +): T = withContext(context) { runInterruptibleInExpectedContext(block) } |
| 56 | + |
| 57 | +private suspend fun <T> runInterruptibleInExpectedContext(block: () -> T): T = |
| 58 | + suspendCoroutineUninterceptedOrReturn sc@{ uCont -> |
| 59 | + try { |
| 60 | + // fast path: no job |
| 61 | + val job = uCont.context[Job] ?: return@sc block() |
| 62 | + // slow path |
| 63 | + val threadState = ThreadState(job) |
| 64 | + try { |
| 65 | + block() |
| 66 | + } finally { |
| 67 | + threadState.clear() |
| 68 | + } |
| 69 | + } catch (e: InterruptedException) { |
| 70 | + throw CancellationException("runInterruptible: interrupted").initCause(e) |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | +private const val WORKING = 0 |
| 75 | +private const val FINISH = 1 |
| 76 | +private const val INTERRUPTING = 2 |
| 77 | +private const val INTERRUPTED = 3 |
| 78 | + |
| 79 | +private class ThreadState : CompletionHandler { |
| 80 | + /* |
| 81 | + === States === |
| 82 | +
|
| 83 | + WORKING: running normally |
| 84 | + FINISH: complete normally |
| 85 | + INTERRUPTING: canceled, going to interrupt this thread |
| 86 | + INTERRUPTED: this thread is interrupted |
| 87 | +
|
| 88 | +
|
| 89 | + === Possible Transitions === |
| 90 | +
|
| 91 | + +----------------+ remember +-------------------------+ |
| 92 | + | WORKING | cancellation listener | WORKING | |
| 93 | + | (thread, null) | -------------------------> | (thread, cancel handle) | |
| 94 | + +----------------+ +-------------------------+ |
| 95 | + | | | |
| 96 | + | cancel cancel | | complete |
| 97 | + | | | |
| 98 | + V | | |
| 99 | + +---------------+ | | |
| 100 | + | INTERRUPTING | <--------------------------------------+ | |
| 101 | + +---------------+ | |
| 102 | + | | |
| 103 | + | interrupt | |
| 104 | + | | |
| 105 | + V V |
| 106 | + +---------------+ +-------------------------+ |
| 107 | + | INTERRUPTED | | FINISH | |
| 108 | + +---------------+ +-------------------------+ |
| 109 | + */ |
| 110 | + private val state: AtomicRef<State> |
| 111 | + |
| 112 | + private data class State(val state: Int, val thread: Thread? = null, val cancelHandle: DisposableHandle? = null) |
| 113 | + |
| 114 | + // We're using a non-primary constructor instead of init block of a primary constructor here, because |
| 115 | + // we need to `return`. |
| 116 | + constructor (job: Job) { |
| 117 | + state = atomic(State(WORKING, Thread.currentThread())) |
| 118 | + // watches the job for cancellation |
| 119 | + val cancelHandle = |
| 120 | + job.invokeOnCompletion(onCancelling = true, invokeImmediately = true, handler = this) |
| 121 | + // remembers the cancel handle or drops it |
| 122 | + state.loop { s -> |
| 123 | + when(s.state) { |
| 124 | + WORKING -> if (state.compareAndSet(s, State(WORKING, s.thread, cancelHandle))) return |
| 125 | + INTERRUPTING, INTERRUPTED -> return |
| 126 | + FINISH -> throw IllegalStateException("impossible state") |
| 127 | + else -> throw IllegalStateException("unknown state") |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + fun clear() { |
| 133 | + state.loop { s -> |
| 134 | + when(s.state) { |
| 135 | + WORKING -> if (state.compareAndSet(s, State(FINISH))) { s.cancelHandle!!.dispose(); return } |
| 136 | + INTERRUPTING -> { /* spin */ } |
| 137 | + INTERRUPTED -> { Thread.interrupted(); return } // no interrupt leak |
| 138 | + FINISH -> throw IllegalStateException("impossible state") |
| 139 | + else -> throw IllegalStateException("unknown state") |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + override fun invoke(cause: Throwable?) = onCancel(cause) |
| 145 | + |
| 146 | + private inline fun onCancel(cause: Throwable?) { |
| 147 | + state.loop { s -> |
| 148 | + when(s.state) { |
| 149 | + WORKING -> { |
| 150 | + if (state.compareAndSet(s, State(INTERRUPTING))) { |
| 151 | + s.thread!!.interrupt() |
| 152 | + state.value = State(INTERRUPTED) |
| 153 | + return |
| 154 | + } |
| 155 | + } |
| 156 | + FINISH -> return |
| 157 | + INTERRUPTING, INTERRUPTED -> return |
| 158 | + else -> throw IllegalStateException("unknown state") |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | +} |
0 commit comments