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'
}
produce runs a producer and closes the
channel when it finishes, normally or with the failure it throws.
A producer that does not use produce catches that failure and
passes it to close(Throwable). for await throws that
failure after
the values already sent, and the code that reads the channel writes the
try/catch. A plain for loop, each,
collect and toList use the same iterator and throw it
too. A Java enhanced for calls Iterator.hasNext(), which
may throw a checked exception that Iterator does not declare.
receive and send still fail with
ChannelClosedException; the failure is that exception's
cause, so a hand-written loop has to
read the cause or the failure is dropped.- Since:
- 6.0.0
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic final classBlocking sender forproduce(int, Consumer). -
Method Summary
Modifier and TypeMethodDescriptionstatic AsyncChannel<Instant>after(long millis) Creates a timer channel: a capacity-1 channel that delivers a single value, theInstantat which it fired, oncemillishas elapsed from this call, and then closes.static AsyncChannel<Instant>Creates a timer channel that fires oncedurationhas elapsed; seeafter(long).booleanclose()Closes this channel.default booleanCloses this channel becausecausefailed the producer.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.default AsyncChannel<T>Returns a new channel that passes only elements matching the predicate.intReturns the number of values currently buffered.intReturns this channel's buffer capacity.default ThrowableReturns the failure passed toclose(Throwable), ornullwhen this channel is open, was closed normally, or does not retain a cause.booleanisClosed()Returnstrueif this channel has been closed.default <R> AsyncChannel<R>Returns a new channel that transforms each element using the function.default AsyncChannel<T>merge(AsyncChannel<? extends T> other) Returns a new channel that receives values from both this channel andother.static <T> AsyncChannel<T>produce(int capacity, Consumer<? super AsyncChannel.Producer<T>> body) Starts a producer for a new channel of the given capacity.static <T> AsyncChannel<T>produce(Consumer<? super AsyncChannel.Producer<T>> body) Starts a producer for a new unbuffered channel.receive()Receives the next value from this channel.Sends a value through this channel.default List<AsyncChannel<T>>Returns two new channels: elements matching the predicate go to the first, non-matching to the second.default AsyncChannel<T>tap(AsyncChannel<T> tap) Returns a new channel that receives all values from this channel while also sending a copy of each value to the tap 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
-
produce
Starts a producer for a new unbuffered channel.The body runs asynchronously.
AsyncChannel.Producer.send(Object)waits until the channel accepts each value. When the body returns, the channel is closed normally. When the body throws, the channel is closed with that failure, after the values already accepted. AChannelClosedExceptionfromsendmeans the channel was closed by its consumer; that is not recorded as a producer failure.- Type Parameters:
T- the payload type- Parameters:
body- the producer; must not benull- Returns:
- the channel the body sends to
- Throws:
NullPointerException- ifbodyis null- Since:
- 6.0.1
- See Also:
-
produce
Starts a producer for a new channel of the given capacity. Seeproduce(Consumer).- Type Parameters:
T- the payload type- Parameters:
capacity- the maximum buffer size; 0 for unbufferedbody- the producer; must not benull- Returns:
- the channel the body sends to
- Throws:
NullPointerException- ifbodyis nullIllegalArgumentException- ifcapacityis negative- Since:
- 6.0.1
-
after
Creates a timer channel: a capacity-1 channel that delivers a single value, theInstantat which it fired, oncemillishas elapsed from this call, and then closes.Its purpose is to make a deadline a branch of a
ChannelSelect, the way Go'stime.Afterdoes, rather than an exception thrown around the whole select byAwaitable.orTimeout(long, TimeUnit):
As a channel, a timer composes with everything a select offers: several timers give per-branch deadlines, a timer may be guarded withdef result = await ChannelSelect.from(work, AsyncChannel.after(100)).select() if (result.index == 1) { // timed out: result.value is the Instant the timer fired }ChannelSelect.Offer.when(java.util.function.BooleanSupplier), andChannelSelect.fair()andChannelSelect.random()treat it like any other ready branch.The clock starts now, not at the first receive, so a timer created once and reused across selects is a fixed deadline shared by every round. For a per-round timeout that re-arms on each call of a select that is held and reused, use the timer offer
ChannelSelect.after(long)instead. A timer that loses a select keeps its value: it fires all the same and holds the instant until received. Firing is one event — the instant is offered and the channel is closed together — so a receiver that takes the value observesisClosed()as true, and further receives fail withChannelClosedExceptionrather than waiting forever. Closing a timer before it fires cancels it. A delay that is not positive has already elapsed, so the channel is returned already holding its instant: it is ready at once, which suits a deadline computed from an absolute time that has already passed.- Parameters:
millis- how long to wait before firing, in milliseconds- Returns:
- a channel that delivers the firing instant and then closes
- Since:
- 6.0.0
- See Also:
-
after
Creates a timer channel that fires oncedurationhas elapsed; seeafter(long).- Parameters:
duration- how long to wait before firing- Returns:
- a channel that delivers the firing instant and then closes
- Throws:
NullPointerException- if duration is null- Since:
- 6.0.0
-
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. When the channel was closed with a failure, that failure is the exception's cause.- 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. When the channel was closed with a failure, that failure is the exception's cause. A loop that catches onlyChannelClosedExceptiondrops the failure unless it readsThrowable.getCause().for awaitthrows the failure itself; the code that reads the channel writes thetry/catch.- 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- See Also:
-
close
Closes this channel becausecausefailed the producer.Values already buffered are still delivered.
receiveandsendthen fail withChannelClosedException, andcauseis that exception's cause.for awaitthrowscauseafter those values. The reading code writes thetry/catch. A normalclose()still ends the loop without throwing.nullmeans a normal close, the same asclose(). Returnstruewhen this call closes the channel. The first close wins, so a later call returnsfalseand leaves any retained failure unchanged.The default implementation calls
close()and returns its result. It does not retaincause. An implementation that does not override this method therefore ends iteration without throwingcause. The channel returned bycreate(int)retainscause. An implementation ofclose()must not call this method unless it also overrides it: the default callsclose()again.- Parameters:
cause- the failure iteration should throw, ornullfor a normal close- Returns:
trueif this call closed the channel- Since:
- 6.0.1
-
getCloseCause
Returns the failure passed toclose(Throwable), ornullwhen this channel is open, was closed normally, or does not retain a cause.The default is
null.receiveandsenddo not throw this failure; it is the cause of theChannelClosedExceptionthey throw.- Returns:
- the retained failure, or
null - Since:
- 6.0.1
-
filter
Returns a new channel that passes only elements matching the predicate. The result closes when this channel does. A failure from this channel or frompredicateis retained, sofor awaitthrows it.- Parameters:
predicate- the filter function- Returns:
- a new filtered channel
- Since:
- 6.0.0
-
map
Returns a new channel that transforms each element using the function. The result closes when this channel does. A failure from this channel or fromtransformis retained, sofor awaitthrows it.- Type Parameters:
R- the output element type- Parameters:
transform- the mapping function- Returns:
- a new transformed channel
- Since:
- 6.0.0
-
merge
Returns a new channel that receives values from both this channel andother. Values are interleaved as they arrive.The output closes when both inputs have closed normally. A failure from either input closes the output with that failure once every value a relay has already taken, and every value buffered on the other input when the failure is seen, has been forwarded. Values sent to the other input after that are not forwarded, so a busy producer cannot hold the failure back. The other input is not closed. A producer still waiting to hand a value over is not released. When both inputs fail, the first failure retained on the output wins. A later normal close does not replace it.
- Parameters:
other- the channel to merge with- Returns:
- a new merged channel
- Throws:
NullPointerException- ifotheris null- Since:
- 6.0.0
-
split
Returns two new channels: elements matching the predicate go to the first, non-matching to the second. Both close when this channel does, and both retain a failure from this channel or frompredicate. Closing one result stops the split and closes the other normally; a failure close of one result is not copied onto the other.- Parameters:
predicate- the split condition- Returns:
- a list of two channels: [matching, non-matching]
- Since:
- 6.0.0
-
tap
Returns a new channel that receives all values from this channel while also sending a copy of each value to the tap channel. Useful for logging, monitoring, or forking a side pipeline. A closed tap is ignored and the pass-through continues. A failure from this channel is retained on the result.- Parameters:
tap- the channel to send copies to- Returns:
- a new pass-through channel
- Since:
- 6.0.0
-