scoop:scoop.concurrent:0.1.0
src/channel.scoop
Selected production source · src/channel.scoop
1
package scoop.concurrent3
import scoop.collections.ArrayDeque4
import scoop.platform.concurrent.Mutex6
/** The result of a non-suspending send attempt. */7
public enum TrySendResult {8
Sent, Full, Closed9
}11
/** A received message, a temporarily empty channel, or a drained closed channel. */12
public enum TryReceiveResult<T> {13
Value(T), Empty, Closed14
}16
/** The channel no longer accepts messages, or has closed and drained. */17
public class ChannelClosedException public constructor(): Exception(Some("channel is closed"))19
/** A FIFO MPMC channel. Zero capacity requires a rendezvous with a receiver. */20
public class Channel<T> public constructor(private val capacity: Long) {21
private val lock = Mutex()22
private val buffer = ArrayDeque<T>()23
private val senders = WaitQueue<ChannelSender<T>>()24
private val receivers = WaitQueue<ChannelReceiver<T>>()25
private var closed = false27
init {28
if (capacity < 0L)29
throw IllegalArgumentException(Some("negative channel capacity"))30
}32
/** Suspends until the message is committed, or cancellation or closure wins. */33
public suspend fun send(value: T) {34
ensureActive()35
suspendCoroutine<Unit> {36
continuation ->37
val sender = ChannelSender(value, continuation)38
val registration =39
currentJobOrNone()?.invokeOnCancellation { error -> cancelSend(sender, error) }40
val notifications = WaitNotifications()41
lock.withLock {42
sender.result.bind(registration, notifications)43
if (sender.result.isPending) {44
when (sendLocked(value, notifications)) {45
case Sent -> {46
sender.value = None47
sender.result.succeed(Unit, notifications)48
}49
case Closed -> {50
sender.value = None51
sender.result.fail(ChannelClosedException(), notifications)52
}53
case Full -> sender.link = Some(senders.append(sender))54
}55
}56
Unit57
}58
notifications.deliver()59
}60
}62
/** Receives the next message, or throws after closure and draining. */63
public suspend fun receive(): T =64
when (receiveOrNone()) {65
case Some(val value) -> value66
case None -> throw ChannelClosedException()67
}69
/** Returns None only after closure and draining, preserving nullable messages. */70
public suspend fun receiveOrNone(): T? {71
ensureActive()72
return suspendCoroutine<T?> {73
continuation ->74
val receiver = ChannelReceiver(continuation)75
val registration =76
currentJobOrNone()?.invokeOnCancellation { error -> cancelReceive(receiver, error) }77
val notifications = WaitNotifications()78
lock.withLock {79
receiver.result.bind(registration, notifications)80
if (receiver.result.isPending) {81
when (receiveLocked(notifications)) {82
case Value(val value) -> receiver.result.succeed(Some(value), notifications)83
case Closed -> receiver.result.succeed(None, notifications)84
case Empty -> receiver.link = Some(receivers.append(receiver))85
}86
}87
Unit88
}89
notifications.deliver()90
}91
}93
/** Attempts a send without suspending or observing the current Job. */94
public fun trySend(value: T): TrySendResult {95
val notifications = WaitNotifications()96
val result = lock.withLock { sendLocked(value, notifications) }97
notifications.deliver()98
return result99
}101
/** Attempts a receive without suspending or observing the current Job. */102
public fun tryReceive(): TryReceiveResult<T> {103
val notifications = WaitNotifications()104
val result = lock.withLock { receiveLocked(notifications) }105
notifications.deliver()106
return result107
}109
/** Rejects pending and future sends; committed buffered messages remain available. */110
public fun close(): Boolean {111
val notifications = WaitNotifications()112
val changed =113
lock.withLock {114
if (closed)115
return@withLock false116
closed = true117
while (!senders.isEmpty) {118
val sender = senders.takeFirst()!!119
sender.link = None120
sender.value = None121
sender.result.fail(ChannelClosedException(), notifications)122
}123
while (!receivers.isEmpty) {124
val receiver = receivers.takeFirst()!!125
receiver.link = None126
receiver.result.succeed(None, notifications)127
}128
true129
}130
notifications.deliver()131
return changed132
}134
private fun sendLocked(value: T, notifications: WaitNotifications): TrySendResult {135
if (closed)136
return TrySendResult.Closed137
when (receivers.takeFirst()) {138
case Some(val receiver) -> {139
receiver.link = None140
receiver.result.succeed(Some(value), notifications)141
return TrySendResult.Sent142
}143
case None -> {}144
}145
if (senders.isEmpty && buffer.size < capacity) {146
buffer.addLast(value)147
return TrySendResult.Sent148
}149
return TrySendResult.Full150
}152
private fun receiveLocked(notifications: WaitNotifications): TryReceiveResult<T> {153
if (!receivers.isEmpty)154
return TryReceiveResult.Empty155
if (buffer.size > 0L) {156
val value = buffer.removeFirst()157
when (senders.takeFirst()) {158
case Some(val sender) -> {159
sender.link = None160
buffer.addLast(sender.value!!)161
sender.value = None162
sender.result.succeed(Unit, notifications)163
}164
case None -> {}165
}166
return TryReceiveResult.Value(value)167
}168
when (senders.takeFirst()) {169
case Some(val sender) -> {170
sender.link = None171
val value = sender.value!!172
sender.value = None173
sender.result.succeed(Unit, notifications)174
return TryReceiveResult.Value(value)175
}176
case None -> {}177
}178
if (closed)179
return TryReceiveResult.Closed180
return TryReceiveResult.Empty181
}183
private fun cancelSend(sender: ChannelSender<T>, error: CancellationException) {184
val notifications = WaitNotifications()185
lock.withLock {186
if (sender.result.isPending) {187
when (sender.link) {188
case Some(val link) -> senders.remove(link)189
case None -> {}190
}191
sender.link = None192
sender.value = None193
sender.result.fail(error, notifications)194
}195
Unit196
}197
notifications.deliver()198
}200
private fun cancelReceive(receiver: ChannelReceiver<T>, error: CancellationException) {201
val notifications = WaitNotifications()202
lock.withLock {203
if (receiver.result.isPending) {204
when (receiver.link) {205
case Some(val link) -> receivers.remove(link)206
case None -> {}207
}208
receiver.link = None209
receiver.result.fail(error, notifications)210
}211
Unit212
}213
notifications.deliver()214
}215
}