public interface AsyncChannel<T>
extends Iterable
An asynchronous channel for inter-task communication with optional buffering.
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:
create() or create(0). Each
send suspends until a matching receive arrives.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.
T - the payload type| Modifiers | Name | Description |
|---|---|---|
class |
AsyncChannel.Producer |
Blocking sender for AsyncChannel.produce. |
| Type Params | Return Type | Name and description |
|---|---|---|
|
public static AsyncChannel<Instant> |
after(long millis)Creates a timer channel: a capacity-1 channel that delivers a single value, the Instant at which it fired, once millis has
elapsed from this call, and then closes. |
|
public static AsyncChannel<Instant> |
after(Duration duration)Creates a timer channel that fires once duration has elapsed;
see after(long). |
|
public boolean |
close()Closes this channel. |
|
public boolean |
close(Throwable cause)Closes this channel because cause failed the producer. |
<T> |
public static AsyncChannel<T> |
create()Creates an unbuffered (rendezvous) channel. |
<T> |
public static AsyncChannel<T> |
create(int capacity)Creates a channel with the specified buffer capacity. |
|
public AsyncChannel<T> |
filter(Predicate<T> predicate)Returns a new channel that passes only elements matching the predicate. |
|
public int |
getBufferedSize()Returns the number of values currently buffered. |
|
public int |
getCapacity()Returns this channel's buffer capacity. |
|
public Throwable |
getCloseCause()Returns the failure passed to close(Throwable), or null
when this channel is open, was closed normally, or does not retain a cause. |
|
public boolean |
isClosed()Returns true if this channel has been closed. |
<R> |
public AsyncChannel<R> |
map(Function<T, R> transform)Returns a new channel that transforms each element using the function. |
|
public AsyncChannel<T> |
merge(AsyncChannel<? extends T> other)Returns a new channel that receives values from both this channel and other. |
<T> |
private public static boolean |
offer(AsyncChannel<? super T> out, T item)Sends item to out. |
<T> |
public static AsyncChannel<T> |
produce(Consumer<? super Producer<T>> body)Starts a producer for a new unbuffered channel. |
<T> |
public static AsyncChannel<T> |
produce(int capacity, Consumer<? super Producer<T>> body)Starts a producer for a new channel of the given capacity. |
<T> |
private public static void |
pump(AsyncChannel<? extends T> source, Predicate<T> step, Consumer<Throwable> close)Reads source until it closes, step returns false,
or step throws, then runs close. |
|
public Awaitable<T> |
receive()Receives the next value from this channel. |
<T> |
private public static void |
relay(AsyncChannel<? extends T> in, AsyncChannel<T> out, AtomicInteger openInputs, MergeRelay self, MergeRelay sibling)Forwards in to out. |
<T> |
private public static void |
runProducer(AsyncChannel<T> channel, Producer<T> producer, Consumer<? super Producer<T>> body)Runs body and closes channel. |
|
public Awaitable<Void> |
send(T value)Sends a value through this channel. |
|
public List<AsyncChannel<T>> |
split(Predicate<T> predicate)Returns two new channels: elements matching the predicate go to the first, non-matching to the second. |
|
public 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 class | Name |
|---|---|
interface Iterable |
forEach, iterator, spliterator |
Creates a timer channel: a capacity-1 channel that delivers a single
value, the Instant at which it fired, once millis has
elapsed from this call, and then closes.
Its purpose is to make a deadline a branch of a ChannelSelect,
the way Go's time.After does, rather than an exception thrown
around the whole select by Awaitable.orTimeout:
def result = await ChannelSelect.from(work, AsyncChannel.after(100)).select()
if (result.index == 1) {
// timed out: result.value is the Instant the timer fired
}
As a channel, a timer composes with everything a select offers: several
timers give per-branch deadlines, a timer may be guarded with
ChannelSelect.Offer#when, and ChannelSelect.fair and
ChannelSelect.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 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 observes isClosed() as true, and further receives fail with ChannelClosedException rather 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.
millis - how long to wait before firing, in milliseconds Creates a timer channel that fires once duration has elapsed;
see after(long).
duration - how long to wait before firingCloses this channel. Idempotent.
Buffered values remain receivable. Pending senders fail with ChannelClosedException. After all buffered values are drained, subsequent receives also fail.
true if this call actually closed the channel Closes this channel because cause failed the producer.
Values already buffered are still delivered. receive and
send then fail with ChannelClosedException, and
cause is that exception's cause. for await throws
cause after those values. The reading code writes the
try/catch. A normal close() still ends the
loop without throwing.
null means a normal close, the same as close().
Returns true when this call closes the channel. The first
close wins, so a later call returns false and leaves any
retained failure unchanged.
The default implementation calls close() and returns its
result. It does not retain cause. An implementation that does
not override this method therefore ends iteration without throwing
cause. The channel returned by create(int) retains
cause. An implementation of close() must not call
this method unless it also overrides it: the default calls
close() again.
cause - the failure iteration should throw, or null for a normal closetrue if this call closed the channelCreates an unbuffered (rendezvous) channel.
Creates a channel with the specified buffer capacity.
capacity - the maximum buffer size; 0 for unbuffered Returns a new channel that passes only elements matching the predicate.
The result closes when this channel does. A failure from this channel
or from predicate is retained, so for await throws it.
predicate - the filter functionReturns the number of values currently buffered.
Returns this channel's buffer capacity.
Returns the failure passed to close(Throwable), or null
when this channel is open, was closed normally, or does not retain a cause.
The default is null. receive and send do not
throw this failure; it is the cause
of the ChannelClosedException they throw.
null Returns true if this channel has been closed.
Returns a new channel that transforms each element using the function.
The result closes when this channel does. A failure from this channel
or from transform is retained, so for await throws it.
transform - the mapping functionR - the output element type Returns a new channel that receives values from both this channel and
other. 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.
other is nullother - the channel to merge with Sends item to out.
false when out is already closed, so the caller
stops without adopting out's close causeStarts a producer for a new unbuffered channel.
The body runs asynchronously. Producer.send 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. A ChannelClosedException
from send means the channel was closed by its consumer; that is
not recorded as a producer failure.
body is nullbody - the producer; must not be nullT - the payload typeStarts a producer for a new channel of the given capacity. See produce(Consumer).
body is nullcapacity is negativecapacity - the maximum buffer size; 0 for unbufferedbody - the producer; must not be nullT - the payload type Reads source until it closes, step returns false,
or step throws, then runs close. A close of source
keeps that close's cause, and null means a normal close. A
throwable from step is the failure to retain. A closed output is
not one of those: step reports it by returning false
(see offer), and that output's own close is left as it is.
Receives the next value from this channel.
The returned Awaitable completes when a value is available.
Receiving from a closed, empty channel fails with
ChannelClosedException. When the channel was closed with a
failure, that failure is the exception's cause. A loop that catches
only ChannelClosedException drops the failure unless it reads
Throwable.getCause. for await throws the failure
itself; the code that reads the channel writes the try/catch.
Forwards in to out. A failure first lets sibling
finish values it has already taken or that are already buffered, then
closes out. A normal end closes out only after every
input has ended the same way.
Runs body and closes channel. The body can throw an
Error or a checked exception; that failure has to close the
channel on this thread rather than escape the executor.
Sends a value through this channel.
The returned Awaitable completes when the value has been delivered to a receiver or buffered. Sending to a closed channel fails immediately with ChannelClosedException. When the channel was closed with a failure, that failure is the exception's cause.
value - the value to send; must not be null 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 from predicate.
Closing one result stops the split and closes the other normally; a
failure close of one result is not copied onto the other.
predicate - the split conditionReturns 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.
tap - the channel to send copies to