|
| 1 | +/* |
| 2 | + * Copyright 2016-2018 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 | + |
| 12 | +/** |
| 13 | + * This is the [CoroutineInterruptController] implementation on JVM. See [CoroutineInterruptController] for detailed |
| 14 | + * description and examples. |
| 15 | + */ |
| 16 | +object CoroutineInterruptible : |
| 17 | + CoroutineInterruptController(), ThreadContextElement<CoroutineInterruptible.ThreadState?> { |
| 18 | + |
| 19 | + /** |
| 20 | + * Update the complete state of a coroutine on JVM. |
| 21 | + * Transforms [InterruptedException] into [CancellationException] for coroutines with this context element. |
| 22 | + */ |
| 23 | + @InternalCoroutinesApi |
| 24 | + override fun updateCoroutineCompleteState(completeState: Any?): Any? = |
| 25 | + if (completeState is CompletedExceptionally && completeState.cause is InterruptedException) |
| 26 | + CompletedExceptionally(CancellationException()) |
| 27 | + else |
| 28 | + completeState |
| 29 | + |
| 30 | + /** |
| 31 | + * Updates context of the current thread. |
| 32 | + * This function is invoked before the coroutine in the specified [context] is resumed in the current thread. |
| 33 | + * Prepares interruption for this execution, watching the [Job] for cancellation and interrupt this executing |
| 34 | + * thread on cancellation. |
| 35 | + */ |
| 36 | + @InternalCoroutinesApi |
| 37 | + override fun updateThreadContext(context: CoroutineContext): ThreadState? { |
| 38 | + // Fast path: no Job in this context |
| 39 | + val job = context[Job] ?: return null |
| 40 | + // Slow path |
| 41 | + val threadState = ThreadState() |
| 42 | + threadState.initInterrupt(job) |
| 43 | + return threadState |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Restores context of the current thread. |
| 48 | + * This function is invoked after the coroutine in the specified [context] is suspended in the current thread. |
| 49 | + * Stops watching the [Job] for cancellation and do clean-up work. |
| 50 | + */ |
| 51 | + @InternalCoroutinesApi |
| 52 | + override fun restoreThreadContext(context: CoroutineContext, oldState: ThreadState?) { |
| 53 | + // Fast path: no Job in this context |
| 54 | + val threadState = oldState ?: return |
| 55 | + // Slow path |
| 56 | + threadState.clearInterrupt() |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Holds the state of executions for interruption. |
| 61 | + */ |
| 62 | + @InternalCoroutinesApi |
| 63 | + class ThreadState { |
| 64 | + fun initInterrupt(job: Job) { |
| 65 | + initInvokeOnCancel(job) |
| 66 | + initThread() |
| 67 | + } |
| 68 | + |
| 69 | + fun clearInterrupt() { |
| 70 | + state.loop { s -> |
| 71 | + when { |
| 72 | + s is Working -> { |
| 73 | + if (state.compareAndSet(s, Finish)) { |
| 74 | + s.cancelHandle?.let { it.dispose() } // no more watching |
| 75 | + return |
| 76 | + } |
| 77 | + } |
| 78 | + s === Interrupting -> Thread.yield() // eases the thread |
| 79 | + s === Interrupted -> { Thread.interrupted(); return } // no interrupt leak |
| 80 | + s === Init || s === Finish -> throw IllegalStateException("impossible state") |
| 81 | + else -> throw IllegalStateException("unknown state") |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + private fun initInvokeOnCancel(job: Job) { |
| 87 | + // watches the job for cancellation |
| 88 | + val cancelHandle = |
| 89 | + job.invokeOnCompletion(onCancelling = true, invokeImmediately = true, handler = CancelHandler()) |
| 90 | + // remembers the cancel handle or drops it |
| 91 | + state.loop { s -> |
| 92 | + when { |
| 93 | + s === Init -> if (state.compareAndSet(s, Working(null, cancelHandle))) return |
| 94 | + s is Working -> if (state.compareAndSet(s, Working(s.thread, cancelHandle))) return |
| 95 | + s === Finish -> { cancelHandle.dispose(); return } // no more watching needed |
| 96 | + s === Interrupting || s === Interrupted -> return |
| 97 | + else -> throw IllegalStateException("unknown state") |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + private fun initThread() { |
| 103 | + val thread = Thread.currentThread() |
| 104 | + state.loop { s -> |
| 105 | + when { |
| 106 | + s === Init -> if (state.compareAndSet(s, Working(thread, null))) return |
| 107 | + s is Working -> if (state.compareAndSet(s, Working(thread, s.cancelHandle))) return |
| 108 | + s === Interrupted -> { thread.interrupt(); return } // interrupted before the thread is set |
| 109 | + s === Finish || s === Interrupting -> throw IllegalStateException("impossible state") |
| 110 | + else -> throw IllegalStateException("unknown state") |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + private inner class CancelHandler : CompletionHandler { |
| 116 | + override fun invoke(cause: Throwable?) { |
| 117 | + state.loop { s -> |
| 118 | + when { |
| 119 | + s === Init || (s is Working && s.thread === null) -> { |
| 120 | + if (state.compareAndSet(s, Interrupted)) |
| 121 | + return |
| 122 | + } |
| 123 | + s is Working -> { |
| 124 | + if (state.compareAndSet(s, Interrupting)) { |
| 125 | + s.thread!!.interrupt() |
| 126 | + state.value = Interrupted |
| 127 | + return |
| 128 | + } |
| 129 | + } |
| 130 | + s === Finish -> return |
| 131 | + s === Interrupting || s === Interrupted -> return |
| 132 | + else -> throw IllegalStateException("unknown state") |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + private val state: AtomicRef<State> = atomic(Init) |
| 139 | + |
| 140 | + private interface State |
| 141 | + // initial state |
| 142 | + private object Init : State |
| 143 | + // cancellation watching is setup and/or the continuation is running |
| 144 | + private data class Working(val thread: Thread?, val cancelHandle: DisposableHandle?) : State |
| 145 | + // the continuation done running without interruption |
| 146 | + private object Finish : State |
| 147 | + // interrupting this thread |
| 148 | + private object Interrupting: State |
| 149 | + // done interrupting |
| 150 | + private object Interrupted: State |
| 151 | + } |
| 152 | +} |
0 commit comments