scoop:scoop.core:0.1.0
src/job.scoop
Selected production source · src/job.scoop
1
/**2
* The terminal exception used for cooperative job cancellation.3
*/4
public class CancellationException public constructor(): Exception(Some("task was cancelled"))6
private const val JOB_CANCELLED: Int = 18
private const val JOB_COMPLETED: Int = 210
/**11
* Tracks a coroutine and its structured children. Completion waits for children; cancellation12
* requests propagate to children and registered handlers.13
*/14
public open class Job internal constructor(15
parent: Job?,16
private val propagatesFailure: Boolean = true17
) {18
private val lock: CoroutineLock = CoroutineLock()19
private var parent: Job? = parent20
private var children: ArrayList<Job>? = None21
private val completionListeners: CoroutineListeners = CoroutineListeners(lock)22
private val cancellationListeners: CoroutineListeners = CoroutineListeners(lock)23
private var bodyEnded: Boolean = false24
private val status: AtomicInt = AtomicInt(0)25
private var cancelling: Int = 026
private var cancellation: CancellationException? = None27
private var failure: Throwable? = None29
private val completed: Boolean get() = (status.load(MemoryOrder.Relaxed) and JOB_COMPLETED) != 031
/**32
* Whether the job and its children have reached a terminal state.33
*/34
public val isCompleted: Boolean get() =35
(status.load(MemoryOrder.Acquire) and JOB_COMPLETED) != 036
/**37
* Whether cancellation has been requested for this job.38
*/39
public val isCancelled: Boolean get() =40
(status.load(MemoryOrder.Acquire) and JOB_CANCELLED) != 042
/**43
* Throws the job's cancellation exception when cancellation has been requested.44
*/45
public fun ensureActive() {46
if ((status.load(MemoryOrder.Acquire) and JOB_CANCELLED) != 0)47
throw cancellation!!48
}50
/**51
* Requests cancellation of this job and its children. Repeated requests preserve the existing52
* cancellation outcome.53
*/54
public fun cancel() {55
requestCancellation(None)56
}58
/**59
* Registers a cancellation handler and returns a disposable registration; an already-cancelled60
* job invokes it immediately.61
*/62
public fun invokeOnCancellation(handler: (CancellationException) -> Unit): Disposable {63
val(listener, callNow, tracked) = lock.withLock { registerCancellationLocked(handler) }64
if (callNow) {65
try {66
listener.fire()67
}68
catch (error: Throwable) {69
if (!tracked)70
throw error71
requestCancellation(Some(error))72
} finally {73
if (tracked) {74
lock.withLock { cancelling -= 1 }75
tryComplete()76
}77
}78
}79
return listener80
}82
private fun registerCancellationLocked(handler: (CancellationException) -> Unit): (83
CoroutineRegistration,84
Boolean,85
Boolean86
) {87
if (!coroutineAbsent(cancellation)) {88
if (!completed)89
cancelling += 190
return (91
CoroutineRegistration(cancellationListeners, { handler(cancellationReason()) }),92
true,93
!completed94
)95
}96
if (completed) {97
val entry =98
CoroutineRegistration(cancellationListeners, { handler(cancellationReason()) })99
entry.takeActionLocked()100
return (entry, false, false)101
}102
val entry = cancellationListeners.addLocked { handler(cancellationReason()) }103
return (entry, false, false)104
}106
private fun cancellationReason(): CancellationException = lock.withLock { cancellation!! }108
internal fun attach(child: Job) {109
val cancelChild =110
lock.withLock {111
if (bodyEnded)112
throw IllegalStateException(Some("coroutine scope is closed"))113
if (coroutineAbsent(children))114
children = Some(ArrayList<Job>())115
children!!.add(child)116
!coroutineAbsent(cancellation)117
}118
if (cancelChild)119
child.cancel()120
}122
private fun removeChild(child: Job) {123
val done =124
lock.withLock {125
when (children) {126
case None -> {}127
case Some(val values) -> {128
var index = 0L129
while (index < values.size) {130
if (values[index] === child) {131
values.removeAt(index)132
break133
}134
index += 1L135
}136
}137
}138
completeLocked()139
}140
publishCompletion(done)141
}143
internal fun finishBody(error: Throwable?) {144
if (coroutineAbsent(error)) {145
val done =146
lock.withLock {147
bodyEnded = true148
completeLocked()149
}150
publishCompletion(done)151
return152
}153
lock.withLock {154
bodyEnded = true;155
cancelling += 1156
}157
try {158
when (error) {159
case Some(val reason) -> requestCancellation(Some(reason))160
case None -> {}161
}162
} finally {163
lock.withLock { cancelling -= 1 }164
tryComplete()165
}166
}168
private fun requestCancellation(error: Throwable?) {169
val dispatch: CoroutineCancellation? =170
lock.withLock {171
if (completed)172
return@withLock None173
var propagate: Throwable? = None174
when (error) {175
case Some(val reason) -> {176
if (!(reason is CancellationException) && coroutineAbsent(failure)) {177
failure = Some(reason)178
propagate = Some(reason)179
}180
}181
case None -> {}182
}183
if (coroutineAbsent(cancellation)) {184
cancellation = Some(CancellationException())185
status.store(JOB_CANCELLED, MemoryOrder.Release)186
}187
cancelling += 1188
Some(189
CoroutineCancellation(190
parent,191
propagate,192
when (children) {193
case Some(val values) -> values.toArray()194
case None -> []195
},196
cancellationListeners.takeLocked()197
)198
)199
}200
when (dispatch) {201
case None -> return202
case Some(val batch) -> {203
try {204
when (batch.failure) {205
case Some(val reason) -> {206
when (batch.parent) {207
case Some(val owner) -> if (propagatesFailure)208
owner.requestCancellation(Some(reason))209
case None -> {}210
}211
}212
case None -> {}213
}214
for (child in batch.children)215
child.cancel()216
if (!coroutineAbsent(batch.listeners))217
for (listener in batch.listeners!!) {218
try {219
listener.fire()220
}221
catch (reason: Throwable) {222
requestCancellation(Some(reason))223
}224
}225
} finally {226
lock.withLock { cancelling -= 1 }227
tryComplete()228
}229
}230
}231
}233
private fun tryComplete() {234
publishCompletion(lock.withLock { completeLocked() })235
}237
private fun completeLocked(): CoroutineCompletion? {238
if (completed || !bodyEnded || cancelling != 0)239
return None240
if (!coroutineAbsent(children) && children!!.size != 0L)241
return None242
val owner = parent243
parent = None244
cancellationListeners.clearLocked()245
val done = Some(CoroutineCompletion(owner, completionListeners.takeLocked()))246
status.store(status.load(MemoryOrder.Relaxed) or JOB_COMPLETED, MemoryOrder.Release)247
return done248
}250
private fun publishCompletion(batch: CoroutineCompletion?) {251
when (batch) {252
case None -> {}253
case Some(val done) -> {254
try {255
when (done.parent) {256
case Some(val owner) -> owner.removeChild(this)257
case None -> {}258
}259
} finally {260
notifyCoroutineListeners(done.listeners)261
}262
}263
}264
}266
internal fun onCompletion(action: () -> Unit): Disposable {267
val(listener, ready) =268
lock.withLock {269
if (completed)270
(CoroutineRegistration(completionListeners, action), true)271
else272
(completionListeners.addLocked(action), false)273
}274
if (ready)275
listener.fire()276
return listener277
}279
internal fun finalFailure(): Throwable? =280
lock.withLock {281
if (!completed)282
throw IllegalStateException(Some("task has not completed"))283
if (!coroutineAbsent(failure))284
return@withLock failure285
when (cancellation) {286
case Some(val reason) -> Some(reason)287
case None -> None288
}289
}291
internal suspend fun joinUncancelled() {292
if (isCompleted)293
return294
suspendCoroutine<Unit> { continuation -> onCompletion { continuation.resume(Unit) } }295
}297
/**298
* Suspends until this job completes, including its children. Joining does not retrieve a299
* deferred result.300
*/301
public suspend fun join() {302
suspendCancellableCoroutine<Unit> {303
continuation ->304
val listener = onCompletion { continuation.tryResume(Unit) }305
continuation.invokeOnCancellation { _ -> listener.dispose() }306
}307
}308
}310
private class CoroutineCancellation(311
val parent: Job?,312
val failure: Throwable?,313
val children: Array<Job>,314
val listeners: ArrayList<CoroutineRegistration>?315
)317
private class CoroutineCompletion(318
val parent: Job?,319
val listeners: ArrayList<CoroutineRegistration>?320
)