Interface AsyncChannel<T>
- Type Parameters:
T- the payload type
- All Superinterfaces:
Iterable<T>
- All Known Implementing Classes:
DefaultAsyncChannel
A channel coordinates producers and consumers without exposing explicit locks or shared mutable state, following the CSP (Communicating Sequential Processes) paradigm popularized by Go's channels.
Channels support both unbuffered (rendezvous) and buffered modes:
- Unbuffered —
create()orcreate(0). Eachsendsuspends until a matchingreceivearrives. - Buffered —
create(n). Values are enqueued until the buffer fills, then senders suspend.
Channels implement Iterable, so they work with for await
and regular for loops — iteration yields received values until the
channel is closed and drained:
def ch = AsyncChannel.create(2)
async { ch.send('a'); ch.send('b'); ch.close() }
for await (item in ch) {
println item // prints 'a', then 'b'
}
- Since:
- 6.0.0
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionbooleanclose()Closes this channel.static <T> AsyncChannel<T>create()Creates an unbuffered (rendezvous) channel.static <T> AsyncChannel<T>create(int capacity) Creates a channel with the specified buffer capacity.intReturns the number of values currently buffered.intReturns this channel's buffer capacity.booleanisClosed()Returnstrueif this channel has been closed.receive()Receives the next value from this channel.Sends a value through this channel.Methods inherited from interface java.lang.Iterable
forEach, iterator, spliterator
-
Method Details
-
create
Creates an unbuffered (rendezvous) channel. -
create
Creates a channel with the specified buffer capacity.- Parameters:
capacity- the maximum buffer size; 0 for unbuffered
-
getCapacity
int getCapacity()Returns this channel's buffer capacity. -
getBufferedSize
int getBufferedSize()Returns the number of values currently buffered. -
isClosed
boolean isClosed()Returnstrueif this channel has been closed. -
send
Sends a value through this channel.The returned
Awaitablecompletes when the value has been delivered to a receiver or buffered. Sending to a closed channel fails immediately withChannelClosedException.- Parameters:
value- the value to send; must not benull- Returns:
- an Awaitable that completes when the send succeeds
- Throws:
NullPointerException- if value is null
-
receive
Receives the next value from this channel.The returned
Awaitablecompletes when a value is available. Receiving from a closed, empty channel fails withChannelClosedException.- Returns:
- an Awaitable that yields the next value
-
close
boolean close()Closes this channel. Idempotent.Buffered values remain receivable. Pending senders fail with
ChannelClosedException. After all buffered values are drained, subsequent receives also fail.- Returns:
trueif this call actually closed the channel
-