Scoop API

scoop:scoop.concurrent:0.1.0

src/channel.scoop

Selected production source · src/channel.scoop

1package scoop.concurrent
3import scoop.collections.ArrayDeque
4import scoop.platform.concurrent.Mutex
6/** The result of a non-suspending send attempt. */
7public enum TrySendResult {
8 Sent, Full, Closed
9}
11/** A received message, a temporarily empty channel, or a drained closed channel. */
12public enum TryReceiveResult<T> {
13 Value(T), Empty, Closed
16/** The channel no longer accepts messages, or has closed and drained. */
17public class ChannelClosedException public constructor(): Exception(Some("channel is closed"))
19/** A FIFO MPMC channel. Zero capacity requires a rendezvous with a receiver. */
20public 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 = false
27 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 = None
47 sender.result.succeed(Unit, notifications)
48 }
49 case Closed -> {
50 sender.value = None
51 sender.result.fail(ChannelClosedException(), notifications)
52 }
53 case Full -> sender.link = Some(senders.append(sender))
54 }
55 }
56 Unit
57 }
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) -> value
66 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 Unit
88 }
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 result
99 }
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 result
107 }
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 false
116 closed = true
117 while (!senders.isEmpty) {
118 val sender = senders.takeFirst()!!
119 sender.link = None
120 sender.value = None
121 sender.result.fail(ChannelClosedException(), notifications)
122 }
123 while (!receivers.isEmpty) {
124 val receiver = receivers.takeFirst()!!
125 receiver.link = None
126 receiver.result.succeed(None, notifications)
127 }
128 true
129 }
130 notifications.deliver()
131 return changed
132 }
134 private fun sendLocked(value: T, notifications: WaitNotifications): TrySendResult {
135 if (closed)
136 return TrySendResult.Closed
137 when (receivers.takeFirst()) {
138 case Some(val receiver) -> {
139 receiver.link = None
140 receiver.result.succeed(Some(value), notifications)
141 return TrySendResult.Sent
142 }
143 case None -> {}
144 }
145 if (senders.isEmpty && buffer.size < capacity) {
146 buffer.addLast(value)
147 return TrySendResult.Sent
148 }
149 return TrySendResult.Full
150 }
152 private fun receiveLocked(notifications: WaitNotifications): TryReceiveResult<T> {
153 if (!receivers.isEmpty)
154 return TryReceiveResult.Empty
155 if (buffer.size > 0L) {
156 val value = buffer.removeFirst()
157 when (senders.takeFirst()) {
158 case Some(val sender) -> {
159 sender.link = None
160 buffer.addLast(sender.value!!)
161 sender.value = None
162 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 = None
171 val value = sender.value!!
172 sender.value = None
173 sender.result.succeed(Unit, notifications)
174 return TryReceiveResult.Value(value)
175 }
176 case None -> {}
177 }
178 if (closed)
179 return TryReceiveResult.Closed
180 return TryReceiveResult.Empty
181 }
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 = None
192 sender.value = None
193 sender.result.fail(error, notifications)
194 }
195 Unit
196 }
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 = None
209 receiver.result.fail(error, notifications)
210 }
211 Unit
212 }
213 notifications.deliver()
214 }