|
| 1 | +package kotlinx.coroutines |
| 2 | + |
| 3 | +import kotlinx.atomicfu.AtomicRef |
| 4 | +import kotlinx.atomicfu.atomic |
| 5 | +import kotlinx.atomicfu.loop |
| 6 | +import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn |
| 7 | + |
| 8 | +/** |
| 9 | + * Makes a blocking code block cancellable (become a cancellation point of the coroutine). |
| 10 | + * |
| 11 | + * The blocking code block will be interrupted and this function will throw [CancellationException] |
| 12 | + * if the coroutine is cancelled. |
| 13 | + * |
| 14 | + * Example: |
| 15 | + * ``` |
| 16 | + * GlobalScope.launch(Dispatchers.IO) { |
| 17 | + * async { |
| 18 | + * // This function will throw [CancellationException]. |
| 19 | + * interruptible { |
| 20 | + * doSomethingUseful() |
| 21 | + * |
| 22 | + * // This blocking procedure will be interrupted when this coroutine is canceled |
| 23 | + * // by Exception thrown by the below async block. |
| 24 | + * doSomethingElseUsefulInterruptible() |
| 25 | + * } |
| 26 | + * } |
| 27 | + * |
| 28 | + * async { |
| 29 | + * delay(500L) |
| 30 | + * throw Exception() |
| 31 | + * } |
| 32 | + * } |
| 33 | + * ``` |
| 34 | + */ |
| 35 | +public suspend fun <T> interruptible(block: () -> T): T = suspendCoroutineUninterceptedOrReturn sc@{ uCont -> |
| 36 | + try { |
| 37 | + // fast path: no job |
| 38 | + val job = uCont.context[Job] ?: return@sc block() |
| 39 | + // slow path |
| 40 | + val threadState = ThreadState().apply { initInterrupt(job) } |
| 41 | + try { |
| 42 | + block() |
| 43 | + } finally { |
| 44 | + threadState.clearInterrupt() |
| 45 | + } |
| 46 | + } catch (e: InterruptedException) { |
| 47 | + throw CancellationException() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +private class ThreadState { |
| 52 | + |
| 53 | + fun initInterrupt(job: Job) { |
| 54 | + // starts with Init |
| 55 | + if (state.value !== Init) throw IllegalStateException("impossible state") |
| 56 | + // remembers this running thread |
| 57 | + state.value = Working(Thread.currentThread(), null) |
| 58 | + // watches the job for cancellation |
| 59 | + val cancelHandle = |
| 60 | + job.invokeOnCompletion(onCancelling = true, invokeImmediately = true, handler = CancelHandler()) |
| 61 | + // remembers the cancel handle or drops it |
| 62 | + state.loop { s -> |
| 63 | + when { |
| 64 | + s is Working -> if (state.compareAndSet(s, Working(s.thread, cancelHandle))) return |
| 65 | + s === Interrupting || s === Interrupted -> return |
| 66 | + s === Init || s === Finish -> throw IllegalStateException("impossible state") |
| 67 | + else -> throw IllegalStateException("unknown state") |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + fun clearInterrupt() { |
| 73 | + state.loop { s -> |
| 74 | + when { |
| 75 | + s is Working -> if (state.compareAndSet(s, Finish)) { s.cancelHandle!!.dispose(); return } |
| 76 | + s === Interrupting -> Thread.yield() // eases the thread |
| 77 | + s === Interrupted -> { Thread.interrupted(); return } // no interrupt leak |
| 78 | + s === Init || s === Finish -> throw IllegalStateException("impossible state") |
| 79 | + else -> throw IllegalStateException("unknown state") |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + private inner class CancelHandler : CompletionHandler { |
| 85 | + override fun invoke(cause: Throwable?) { |
| 86 | + state.loop { s -> |
| 87 | + when { |
| 88 | + s is Working -> { |
| 89 | + if (state.compareAndSet(s, Interrupting)) { |
| 90 | + s.thread!!.interrupt() |
| 91 | + state.value = Interrupted |
| 92 | + return |
| 93 | + } |
| 94 | + } |
| 95 | + s === Finish -> return |
| 96 | + s === Interrupting || s === Interrupted -> return |
| 97 | + s === Init -> throw IllegalStateException("impossible state") |
| 98 | + else -> throw IllegalStateException("unknown state") |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + private val state: AtomicRef<State> = atomic(Init) |
| 105 | + |
| 106 | + private interface State |
| 107 | + // initial state |
| 108 | + private object Init : State |
| 109 | + // cancellation watching is setup and/or the continuation is running |
| 110 | + private data class Working(val thread: Thread?, val cancelHandle: DisposableHandle?) : State |
| 111 | + // the continuation done running without interruption |
| 112 | + private object Finish : State |
| 113 | + // interrupting this thread |
| 114 | + private object Interrupting: State |
| 115 | + // done interrupting |
| 116 | + private object Interrupted: State |
| 117 | +} |
0 commit comments