You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/04/29 05:25:23 UTC
(groovy) branch master updated: GROOVY-11953: Integrated Concurrency and Parallel Processing (optional Publisher pieces)
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/master by this push:
new a71d56f69d GROOVY-11953: Integrated Concurrency and Parallel Processing (optional Publisher pieces)
a71d56f69d is described below
commit a71d56f69d4b604f91bbb156b5ac4b554d072005
Author: Paul King <pa...@asert.com.au>
AuthorDate: Fri Apr 17 16:52:08 2026 +1000
GROOVY-11953: Integrated Concurrency and Parallel Processing (optional Publisher pieces)
---
src/main/java/groovy/concurrent/Agent.java | 102 +++++++-
.../java/groovy/concurrent/BroadcastChannel.java | 183 +++++++++++++++
src/spec/doc/core-async-await.adoc | 38 ++-
src/spec/doc/core-concurrent-actors.adoc | 34 +++
src/spec/doc/core-concurrent-dataflow.adoc | 47 ++++
.../groovy/concurrent/AgentChangesTest.groovy | 206 ++++++++++++++++
.../BroadcastChannelAsPublisherTest.groovy | 221 +++++++++++++++++
.../http/MultiExchangeTickerEndToEndTest.groovy | 261 +++++++++++++++++++++
8 files changed, 1085 insertions(+), 7 deletions(-)
diff --git a/src/main/java/groovy/concurrent/Agent.java b/src/main/java/groovy/concurrent/Agent.java
index 74d638dfdd..b60f539e46 100644
--- a/src/main/java/groovy/concurrent/Agent.java
+++ b/src/main/java/groovy/concurrent/Agent.java
@@ -18,6 +18,7 @@
*/
package groovy.concurrent;
+import org.apache.groovy.runtime.async.AsyncSupport;
import org.apache.groovy.runtime.async.GroovyPromise;
import java.util.Objects;
@@ -25,6 +26,9 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.concurrent.Flow;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;
@@ -63,9 +67,15 @@ import java.util.function.Function;
*/
public final class Agent<T> {
+ /** Default per-subscriber buffer size for {@link #changes()}. */
+ public static final int DEFAULT_CHANGES_BUFFER = 256;
+
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final ExecutorService updateExecutor;
+ private final Object lifecycleLock = new Object();
private volatile T value;
+ private volatile SubmissionPublisher<T> changesPublisher;
+ private volatile boolean shutdownInvoked;
private Agent(T initialValue, ExecutorService executor) {
this.value = initialValue;
@@ -179,11 +189,74 @@ public final class Agent<T> {
/**
* Shuts down the agent's update executor. No further updates will
* be accepted. Pending updates are executed before shutdown completes.
+ * The changes publisher (if any subscribers attached) is closed after
+ * pending updates drain, signalling {@code onComplete} to all live
+ * subscribers. Calling {@code shutdown()} more than once is a no-op.
*/
public void shutdown() {
+ SubmissionPublisher<T> p;
+ synchronized (lifecycleLock) {
+ if (shutdownInvoked) return;
+ shutdownInvoked = true;
+ p = changesPublisher;
+ }
+ if (p != null) {
+ // Submit close as a terminator task so it runs after any queued
+ // updates have drained — ensures applyUpdate never offers to a
+ // publisher that has already been closed.
+ try {
+ updateExecutor.execute(p::close);
+ } catch (RejectedExecutionException ex) {
+ p.close();
+ }
+ }
updateExecutor.shutdown();
}
+ /**
+ * Returns a {@link Flow.Publisher} that emits the agent's value after
+ * every successful update. The publisher is hot and per-subscriber:
+ * <ul>
+ * <li>Subscribers see only changes that occur after they subscribe;
+ * the current value at subscription time is <em>not</em> replayed.</li>
+ * <li>Each subscriber gets an independent buffer (default
+ * {@value #DEFAULT_CHANGES_BUFFER} items).</li>
+ * <li>Slow subscribers drop the most recent value rather than
+ * blocking the agent's update thread. Values already buffered
+ * are delivered in order; only newly-offered values that cannot
+ * fit are discarded.</li>
+ * <li>Closes (signals {@code onComplete}) when {@link #shutdown()} is
+ * called. If {@code changes()} is first called after
+ * {@code shutdown()}, the returned publisher is already closed
+ * and subscribers receive {@code onComplete} immediately.</li>
+ * </ul>
+ * <p>
+ * Typical use:
+ * <pre>{@code
+ * for await (newValue in agent.changes()) {
+ * log.info "Agent value is now {}", newValue
+ * }
+ * }</pre>
+ *
+ * @return a hot publisher of state transitions
+ * @since 6.0.0
+ */
+ public Flow.Publisher<T> changes() {
+ SubmissionPublisher<T> p = changesPublisher;
+ if (p == null) {
+ synchronized (lifecycleLock) {
+ p = changesPublisher;
+ if (p == null) {
+ p = new SubmissionPublisher<>(
+ AsyncSupport.getExecutor(), DEFAULT_CHANGES_BUFFER);
+ if (shutdownInvoked) p.close();
+ changesPublisher = p;
+ }
+ }
+ }
+ return p;
+ }
+
@Override
public String toString() {
return "Agent[" + get() + "]";
@@ -191,12 +264,39 @@ public final class Agent<T> {
private T applyUpdate(Function<T, T> updateFn) {
rwLock.writeLock().lock();
+ T newValue;
try {
value = updateFn.apply(value);
- return value;
+ newValue = value;
} finally {
rwLock.writeLock().unlock();
}
+ SubmissionPublisher<T> p = changesPublisher;
+ if (p != null) {
+ // Two distinct edge cases handled here, on purpose:
+ //
+ // (a) Slow-subscriber drop policy. The onDrop predicate
+ // `(sub, item) -> false` tells SubmissionPublisher.offer
+ // NOT to retry when a subscriber's per-subscriber buffer
+ // is full — i.e. drop the emission for that lagging
+ // subscriber. This is the documented contract: the agent's
+ // serial update loop must never back-pressure on a slow
+ // downstream.
+ //
+ // (b) Close-vs-offer race. Between this thread reading
+ // `changesPublisher` (above) and calling `offer`, another
+ // thread can run `shutdown()` and close the publisher. The
+ // resulting IllegalStateException is intentionally
+ // swallowed: the publisher is gone, this emission is
+ // moot, and the close path is responsible for
+ // onComplete-ing remaining subscribers.
+ try {
+ p.offer(newValue, (sub, item) -> false);
+ } catch (IllegalStateException ignore) {
+ // see (b) above
+ }
+ }
+ return newValue;
}
/**
diff --git a/src/main/java/groovy/concurrent/BroadcastChannel.java b/src/main/java/groovy/concurrent/BroadcastChannel.java
index 77e59a76d7..0ce163b907 100644
--- a/src/main/java/groovy/concurrent/BroadcastChannel.java
+++ b/src/main/java/groovy/concurrent/BroadcastChannel.java
@@ -18,11 +18,16 @@
*/
package groovy.concurrent;
+import org.apache.groovy.runtime.async.AsyncSupport;
import org.apache.groovy.runtime.async.GroovyPromise;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Flow;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
/**
* A one-to-many broadcast channel where each value sent is delivered
@@ -140,4 +145,182 @@ public final class BroadcastChannel<T> {
public int getSubscriberCount() {
return subscribers.size();
}
+
+ /**
+ * Returns a {@link Flow.Publisher} view of this broadcast channel. Each
+ * call to {@link Flow.Publisher#subscribe(Flow.Subscriber)} on the returned
+ * publisher creates a new {@link AsyncChannel} subscriber under the hood,
+ * draining values to the downstream subscriber according to its requested
+ * demand.
+ * <p>
+ * Semantics:
+ * <ul>
+ * <li>Cold per-subscribe binding: each subscription starts seeing values
+ * from the moment it subscribes (consistent with
+ * {@link #subscribe()}).</li>
+ * <li>Backpressure: respects {@code request(n)}; the worker blocks the
+ * broadcast send when no demand exists (sender-side backpressure).</li>
+ * <li>Cancellation: closes this subscriber's channel and removes it
+ * from the broadcast's subscriber set.</li>
+ * <li>Completion: signals {@code onComplete} when the broadcast channel
+ * is closed and the per-subscriber buffer drained.</li>
+ * </ul>
+ * <p>
+ * <b>Backpressure policy (important).</b> This bridge uses lossless,
+ * sender-gated backpressure: {@link #send(Object)} awaits delivery to
+ * every live subscriber, and each per-subscriber channel has a bounded
+ * buffer (default 16). A subscriber that never calls {@code request(n)},
+ * or that requests slowly, will fill its buffer; once full, the
+ * subscriber's channel suspends its backing {@code send}, which in turn
+ * stalls {@code BroadcastChannel.send(...)} for <em>all</em>
+ * subscribers. In other words, the slowest subscriber controls producer
+ * throughput.
+ * <p>
+ * This is intentional and matches the point-to-point semantics of
+ * {@link #subscribe()}: values are neither dropped nor reordered. If
+ * you need decoupled per-subscriber policies (drop-newest, drop-oldest,
+ * latest-only, or unbounded buffering), wrap the publisher with a
+ * Reactive Streams operator of your choice, or use a subscriber that
+ * drains promptly with {@code request(Long.MAX_VALUE)}.
+ *
+ * @return a {@code Flow.Publisher} backed by per-subscriber channels
+ * @since 6.0.0
+ */
+ public Flow.Publisher<T> asPublisher() {
+ return new BroadcastFlowPublisher();
+ }
+
+ private final class BroadcastFlowPublisher implements Flow.Publisher<T> {
+ @Override
+ public void subscribe(Flow.Subscriber<? super T> downstream) {
+ Objects.requireNonNull(downstream, "subscriber must not be null");
+ AsyncChannel<T> channel;
+ try {
+ channel = BroadcastChannel.this.subscribe();
+ } catch (ChannelClosedException e) {
+ downstream.onSubscribe(NOOP_SUBSCRIPTION);
+ downstream.onError(e);
+ return;
+ }
+ new BroadcastFlowSubscription<>(BroadcastChannel.this, channel, downstream).start();
+ }
+ }
+
+ private static final Flow.Subscription NOOP_SUBSCRIPTION = new Flow.Subscription() {
+ @Override public void request(long n) { }
+ @Override public void cancel() { }
+ };
+
+ /**
+ * Per-subscriber bridge that converts a backing {@link AsyncChannel} into
+ * a Reactive Streams subscription with demand tracking.
+ */
+ private static final class BroadcastFlowSubscription<T> implements Flow.Subscription {
+ private final BroadcastChannel<T> owner;
+ private final AsyncChannel<T> channel;
+ private final Flow.Subscriber<? super T> subscriber;
+ private final AtomicLong demand = new AtomicLong();
+ private final AtomicBoolean cancelled = new AtomicBoolean();
+ private final AtomicReference<Throwable> terminalError = new AtomicReference<>();
+ private final Object lock = new Object();
+
+ BroadcastFlowSubscription(BroadcastChannel<T> owner, AsyncChannel<T> channel, Flow.Subscriber<? super T> subscriber) {
+ this.owner = owner;
+ this.channel = channel;
+ this.subscriber = subscriber;
+ }
+
+ void start() {
+ subscriber.onSubscribe(this);
+ AsyncSupport.getExecutor().execute(this::drain);
+ }
+
+ @Override
+ public void request(long n) {
+ if (n <= 0) {
+ // Reactive Streams §3.9 violation. Route the terminal error
+ // through the drain thread (§1.3 requires onNext / onError /
+ // onComplete signals to be serialised); calling
+ // subscriber.onError here would race a concurrent onNext.
+ terminalError.compareAndSet(null, new IllegalArgumentException(
+ "Reactive Streams §3.9: request must be positive, got " + n));
+ synchronized (lock) { lock.notifyAll(); }
+ return;
+ }
+ long prev, next;
+ do {
+ prev = demand.get();
+ next = prev + n;
+ if (next < 0) next = Long.MAX_VALUE; // saturate on overflow
+ } while (!demand.compareAndSet(prev, next));
+ synchronized (lock) { lock.notifyAll(); }
+ }
+
+ @Override
+ public void cancel() {
+ if (!cancelled.compareAndSet(false, true)) return;
+ owner.subscribers.remove(channel);
+ channel.close();
+ synchronized (lock) { lock.notifyAll(); }
+ }
+
+ private void drain() {
+ try {
+ while (!cancelled.get()) {
+ // Caller injected a terminal error via request(n<=0) — emit and stop.
+ Throwable terminal = terminalError.get();
+ if (terminal != null) {
+ subscriber.onError(terminal);
+ cancel();
+ return;
+ }
+ // RS §1.7: terminal completion must not depend on demand.
+ // If the upstream channel has closed and drained, emit
+ // onComplete even when demand == 0.
+ if (channel.isClosed() && channel.getBufferedSize() == 0) {
+ subscriber.onComplete();
+ cancel();
+ return;
+ }
+ if (demand.get() == 0) {
+ synchronized (lock) {
+ if (demand.get() == 0 && !cancelled.get()
+ && terminalError.get() == null
+ && !(channel.isClosed() && channel.getBufferedSize() == 0)) {
+ // Bounded wait so we periodically re-check upstream
+ // close even if no request(n) ever arrives.
+ lock.wait(100L);
+ }
+ }
+ continue;
+ }
+ T item;
+ try {
+ item = AsyncSupport.await(channel.receive());
+ } catch (ChannelClosedException e) {
+ if (!cancelled.get()) {
+ subscriber.onComplete();
+ cancel();
+ }
+ return;
+ }
+ if (cancelled.get()) return;
+ subscriber.onNext(item);
+ long current = demand.get();
+ if (current != Long.MAX_VALUE) demand.decrementAndGet();
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ if (!cancelled.get()) {
+ subscriber.onError(e);
+ cancel();
+ }
+ } catch (Throwable t) {
+ if (!cancelled.get()) {
+ subscriber.onError(t);
+ cancel();
+ }
+ }
+ }
+ }
}
diff --git a/src/spec/doc/core-async-await.adoc b/src/spec/doc/core-async-await.adoc
index 3e14dd71c7..c05c756d57 100644
--- a/src/spec/doc/core-async-await.adoc
+++ b/src/spec/doc/core-async-await.adoc
@@ -273,10 +273,35 @@ include::../test/AsyncAwaitSpecTest.groovy[tags=for_await_generator,indent=0]
----
The key value of `for await` is with **reactive types** (Reactor `Flux`, RxJava
-`Observable`) where it automatically converts the source to a blocking iterable
-via the adapter SPI. Without `for await`, you would need to call the conversion
-manually (e.g., `flux.toIterable()`). For generators and plain collections,
-a regular `for` loop works identically.
+`Observable`, `java.util.concurrent.Flow.Publisher`) where it automatically
+converts the source to a blocking iterable via the adapter SPI. Without
+`for await`, you would need to call the conversion manually (e.g.,
+`flux.toIterable()`). For generators and plain collections, a regular `for`
+loop works identically.
+
+The JDK's `Flow.Publisher` is supported out of the box — no adapter module
+needed. This means streams exposed by built-in sources such as
+`Agent.changes()` (see xref:actors-agent[]) and `BroadcastChannel.asPublisher()`
+(see xref:dataflow-broadcast[]), or any third-party publisher using the JDK
+interfaces, compose directly with `for await` and `await`:
+
+[source,groovy]
+----
+import groovy.concurrent.Agent
+
+def agent = Agent.create(0)
+try {
+ async {
+ 3.times { agent.send { it + 1 } }
+ agent.shutdown()
+ }
+ for await (v in agent.changes()) {
+ println "value is now $v"
+ }
+} finally {
+ agent.shutdown()
+}
+----
[[async-timeouts]]
=== Timeouts and Delays
@@ -307,8 +332,9 @@ include::../test/AsyncAwaitSpecTest.groovy[tags=delay,indent=0]
=== Framework Adapters
`await` natively understands `Awaitable`, `CompletableFuture`, `CompletionStage`,
-and `Future`. Third-party async types can be supported by implementing the
-`AwaitableAdapter` SPI and registering it via
+and `Future`. `for await` natively understands `java.util.concurrent.Flow.Publisher`
+in addition to regular `Iterable` sources. Third-party async types can be
+supported by implementing the `AwaitableAdapter` SPI and registering it via
`META-INF/services/groovy.concurrent.AwaitableAdapter`.
Drop-in adapter modules are provided for:
diff --git a/src/spec/doc/core-concurrent-actors.adoc b/src/spec/doc/core-concurrent-actors.adoc
index ac3fe4c237..2493b70112 100644
--- a/src/spec/doc/core-concurrent-actors.adoc
+++ b/src/spec/doc/core-concurrent-actors.adoc
@@ -93,6 +93,40 @@ inventory.send { state ->
assert await(inventory.getAsync()) == [apples: 20, bananas: 10]
----
+=== Observing state changes
+
+An agent exposes a `Flow.Publisher<T>` of state transitions via
+`changes()`. Each successful update emits the new value to every
+subscriber that is already subscribed at the time of the update. The
+stream is hot (no replay of prior state), per-subscriber buffered,
+and closes with `onComplete` when `shutdown()` is called:
+
+[source,groovy]
+----
+def agent = Agent.create(0)
+try {
+ async {
+ 3.times { agent.send { it + 1 } }
+ Thread.sleep(50)
+ agent.shutdown()
+ }
+ def seen = []
+ for await (v in agent.changes()) {
+ seen << v
+ }
+ assert seen == [1, 2, 3]
+} finally {
+ agent.shutdown()
+}
+----
+
+Slow subscribers drop newly-offered values rather than backpressuring
+the agent's update loop — buffered values are still delivered in order,
+but the most recent update may be skipped if a subscriber's buffer is
+full (default size 256). If `changes()` is first called after
+`shutdown()`, the returned publisher is already closed and subscribers
+receive `onComplete` immediately.
+
[[actors-actor]]
== Actor
diff --git a/src/spec/doc/core-concurrent-dataflow.adoc b/src/spec/doc/core-concurrent-dataflow.adoc
index 7e2858f4fd..176f4492cc 100644
--- a/src/spec/doc/core-concurrent-dataflow.adoc
+++ b/src/spec/doc/core-concurrent-dataflow.adoc
@@ -265,3 +265,50 @@ for await (msg in sub2) { println "Sub2: $msg" }
----
Late subscribers only receive messages sent after they subscribe.
+
+=== Flow.Publisher interop
+
+A `BroadcastChannel` can also be exposed as a `java.util.concurrent.Flow.Publisher`
+via `asPublisher()`. Each call to `subscribe(Flow.Subscriber)` on the returned
+publisher creates a new per-subscriber `AsyncChannel` under the hood and respects
+standard Reactive Streams demand (`request(n)`):
+
+[source,groovy]
+----
+def broadcast = BroadcastChannel.create()
+def publisher = broadcast.asPublisher()
+
+// Compose with any Reactive Streams operator, or consume with `for await`:
+for await (msg in publisher) {
+ println "Got: $msg"
+}
+----
+
+[WARNING]
+====
+*Backpressure policy.* The publisher bridge uses _lossless, sender-gated_
+backpressure: `send()` awaits delivery to every live subscriber, and each
+per-subscriber channel has a bounded buffer (default 16). A subscriber that
+never calls `request(n)` — or requests slowly — will fill its buffer, after
+which `broadcast.send(...)` stalls for *all* subscribers until that
+subscriber catches up. In other words, the slowest subscriber controls
+producer throughput.
+
+This matches the point-to-point semantics of `subscribe()` (values are
+neither dropped nor reordered). If you need decoupled per-subscriber
+policies (drop-newest, drop-oldest, latest-only, or unbounded buffering),
+wrap the publisher with a Reactive Streams operator of your choice, or use
+a subscriber that drains promptly with `request(Long.MAX_VALUE)`.
+====
+
+[NOTE]
+====
+*Terminal signals.* Per Reactive Streams §1.7, terminal completion is
+not gated by demand: once the underlying `BroadcastChannel` is closed
+and the per-subscriber buffer is drained, the subscriber receives
+`onComplete` even if it has no outstanding `request(n)`. Likewise,
+`onError` for a spec-violating `request(n <= 0)` (§3.9) is signalled
+through the same single-threaded delivery path as `onNext` /
+`onComplete`, preserving §1.3 signal serialisation; subscribers do
+not see those signals racing on the caller's thread.
+====
diff --git a/src/test/groovy/groovy/concurrent/AgentChangesTest.groovy b/src/test/groovy/groovy/concurrent/AgentChangesTest.groovy
new file mode 100644
index 0000000000..0a53d56744
--- /dev/null
+++ b/src/test/groovy/groovy/concurrent/AgentChangesTest.groovy
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.concurrent
+
+import org.junit.jupiter.api.Test
+
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Flow
+import java.util.concurrent.TimeUnit
+
+import static groovy.test.GroovyAssert.assertScript
+
+final class AgentChangesTest {
+
+ @Test
+ void emitsValueAfterEachUpdate() {
+ Agent<Integer> agent = Agent.create(0)
+ try {
+ List<Integer> received = Collections.synchronizedList([])
+ CountDownLatch sawThree = new CountDownLatch(3)
+
+ // SubmissionPublisher.subscribe() registers the subscriber
+ // synchronously, so subsequent offers reach it without further
+ // synchronisation needed here.
+ agent.changes().subscribe(new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(Integer item) { received << item; sawThree.countDown() }
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() {}
+ })
+
+ agent.send { it + 1 }
+ agent.send { it + 1 }
+ agent.send { it + 1 }
+
+ assert sawThree.await(2, TimeUnit.SECONDS)
+ assert received == [1, 2, 3]
+ } finally {
+ agent.shutdown()
+ }
+ }
+
+ @Test
+ void doesNotReplayPriorChangesToLateSubscriber() {
+ Agent<Integer> agent = Agent.create(0)
+ try {
+ agent.send { it + 100 }
+ // Wait for the update to land before subscribing
+ assert org.apache.groovy.runtime.async.AsyncSupport.await(agent.getAsync()) == 100
+
+ List<Integer> received = Collections.synchronizedList([])
+ CountDownLatch sawOne = new CountDownLatch(1)
+ agent.changes().subscribe(new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(Integer item) { received << item; sawOne.countDown() }
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() {}
+ })
+
+ agent.send { it + 1 }
+ assert sawOne.await(2, TimeUnit.SECONDS)
+ assert received == [101]
+ } finally {
+ agent.shutdown()
+ }
+ }
+
+ @Test
+ void shutdownClosesPublisher() {
+ Agent<Integer> agent = Agent.create(0)
+ CountDownLatch completed = new CountDownLatch(1)
+ agent.changes().subscribe(new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(Integer item) {}
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() { completed.countDown() }
+ })
+ agent.shutdown()
+ assert completed.await(2, TimeUnit.SECONDS)
+ }
+
+ @Test
+ void pendingUpdatesAreDeliveredBeforeShutdownCloses() {
+ // Regression for race where shutdown() closed the publisher before
+ // queued updates had run, causing applyUpdate's offer() to throw
+ // IllegalStateException and drop emissions silently.
+ Agent<Integer> agent = Agent.create(0)
+ int count = 50
+ List<Integer> received = Collections.synchronizedList([])
+ CountDownLatch completed = new CountDownLatch(1)
+
+ agent.changes().subscribe(new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(Integer item) { received << item }
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() { completed.countDown() }
+ })
+
+ count.times { agent.send { it + 1 } }
+ agent.shutdown()
+
+ assert completed.await(5, TimeUnit.SECONDS)
+ assert received.size() == count
+ assert received == (1..count).toList()
+ }
+
+ @Test
+ void changesAfterShutdownCompletesImmediately() {
+ // Regression for lazy changes() creating a publisher after shutdown
+ // that was never closed, leaving subscribers hanging.
+ Agent<Integer> agent = Agent.create(0)
+ agent.shutdown()
+
+ CountDownLatch completed = new CountDownLatch(1)
+ agent.changes().subscribe(new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(Integer item) {}
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() { completed.countDown() }
+ })
+
+ assert completed.await(2, TimeUnit.SECONDS)
+ }
+
+ @Test
+ void doubleShutdownIsSafe() {
+ Agent<Integer> agent = Agent.create(0)
+ agent.shutdown()
+ agent.shutdown() // must not throw
+ }
+
+ @Test
+ void multipleSubscribersEachReceiveAll() {
+ Agent<String> agent = Agent.create('init')
+ try {
+ List<String> a = Collections.synchronizedList([])
+ List<String> b = Collections.synchronizedList([])
+ CountDownLatch latchA = new CountDownLatch(2)
+ CountDownLatch latchB = new CountDownLatch(2)
+
+ agent.changes().subscribe(sink(a, latchA))
+ agent.changes().subscribe(sink(b, latchB))
+
+ agent.send { 'hello' }
+ agent.send { 'world' }
+
+ assert latchA.await(2, TimeUnit.SECONDS)
+ assert latchB.await(2, TimeUnit.SECONDS)
+ assert a == ['hello', 'world']
+ assert b == ['hello', 'world']
+ } finally {
+ agent.shutdown()
+ }
+ }
+
+ @Test
+ void forAwaitOverChanges() {
+ // End-to-end via the FlowPublisherAdapter
+ assertScript '''
+ import groovy.concurrent.Agent
+
+ def agent = Agent.create(0)
+ try {
+ def collected = []
+ async {
+ Thread.sleep(30) // let consumer subscribe
+ 3.times { agent.send { it + 1 } }
+ Thread.sleep(50)
+ agent.shutdown()
+ }
+
+ for await (val in agent.changes()) {
+ collected << val
+ }
+ assert collected == [1, 2, 3]
+ } finally {
+ agent.shutdown()
+ }
+ '''
+ }
+
+ private Flow.Subscriber<String> sink(List<String> sink, CountDownLatch latch) {
+ return new Flow.Subscriber<String>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(String item) { sink << item; latch.countDown() }
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() {}
+ }
+ }
+}
diff --git a/src/test/groovy/groovy/concurrent/BroadcastChannelAsPublisherTest.groovy b/src/test/groovy/groovy/concurrent/BroadcastChannelAsPublisherTest.groovy
new file mode 100644
index 0000000000..d45c79bebb
--- /dev/null
+++ b/src/test/groovy/groovy/concurrent/BroadcastChannelAsPublisherTest.groovy
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.concurrent
+
+import org.junit.jupiter.api.Test
+
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Flow
+import java.util.concurrent.TimeUnit
+
+import static groovy.test.GroovyAssert.assertScript
+
+final class BroadcastChannelAsPublisherTest {
+
+ /** Spin until {@code cond} is true or the timeout elapses. */
+ private static void waitUntil(long timeoutMs = 2000, Closure<Boolean> cond) {
+ long deadline = System.currentTimeMillis() + timeoutMs
+ while (!cond.call()) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("waitUntil timed out after ${timeoutMs}ms")
+ }
+ Thread.sleep(2)
+ }
+ }
+
+ @Test
+ void deliversValuesToSingleSubscriber() {
+ BroadcastChannel<String> broadcast = BroadcastChannel.create()
+ Flow.Publisher<String> publisher = broadcast.asPublisher()
+
+ List<String> received = []
+ CountDownLatch done = new CountDownLatch(1)
+
+ publisher.subscribe(new Flow.Subscriber<String>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(String item) { received << item }
+ @Override void onError(Throwable t) { done.countDown() }
+ @Override void onComplete() { done.countDown() }
+ })
+
+ // BroadcastChannel.subscribe() registers the per-subscriber channel
+ // synchronously, so subsequent sends are buffered for the new
+ // subscriber even before its drain task starts.
+ broadcast.send('a')
+ broadcast.send('b')
+ broadcast.send('c')
+ broadcast.close()
+
+ assert done.await(2, TimeUnit.SECONDS)
+ assert received == ['a', 'b', 'c']
+ }
+
+ @Test
+ void multipleSubscribersEachReceiveAll() {
+ BroadcastChannel<Integer> broadcast = BroadcastChannel.create()
+ Flow.Publisher<Integer> publisher = broadcast.asPublisher()
+
+ List<Integer> a = []
+ List<Integer> b = []
+ CountDownLatch done = new CountDownLatch(2)
+
+ def subscriber = { List<Integer> sink ->
+ return new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(Integer item) { sink << item }
+ @Override void onError(Throwable t) { done.countDown() }
+ @Override void onComplete() { done.countDown() }
+ }
+ }
+
+ publisher.subscribe(subscriber(a))
+ publisher.subscribe(subscriber(b))
+
+ (1..3).each { broadcast.send(it) }
+ broadcast.close()
+
+ assert done.await(2, TimeUnit.SECONDS)
+ assert a == [1, 2, 3]
+ assert b == [1, 2, 3]
+ }
+
+ @Test
+ void honoursBackpressure() {
+ BroadcastChannel<Integer> broadcast = BroadcastChannel.create()
+ Flow.Publisher<Integer> publisher = broadcast.asPublisher()
+
+ List<Integer> received = []
+ CountDownLatch firstBatch = new CountDownLatch(2)
+ CountDownLatch done = new CountDownLatch(1)
+ def subscriptionRef = new java.util.concurrent.atomic.AtomicReference<Flow.Subscription>()
+
+ publisher.subscribe(new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { subscriptionRef.set(s); s.request(2) }
+ @Override void onNext(Integer item) { received << item; firstBatch.countDown() }
+ @Override void onError(Throwable t) { done.countDown() }
+ @Override void onComplete() { done.countDown() }
+ })
+
+ // send four values; subscriber only requested 2 — extras must wait
+ Thread.startDaemon {
+ (1..4).each { broadcast.send(it) }
+ }
+
+ assert firstBatch.await(2, TimeUnit.SECONDS)
+ // Negative check: ensure no further onNext fires while demand is zero.
+ // This is genuinely a "nothing happens within X ms" assertion, so a
+ // small bounded wait is appropriate.
+ Thread.sleep(50)
+ assert received == [1, 2]
+
+ // Request the rest
+ subscriptionRef.get().request(Long.MAX_VALUE)
+ broadcast.close()
+
+ assert done.await(2, TimeUnit.SECONDS)
+ assert received == [1, 2, 3, 4]
+ }
+
+ @Test
+ void cancelledSubscribersAreRemovedFromList() {
+ // Regression: asPublisher() subscriptions used to leak their backing
+ // AsyncChannel in the parent's subscribers list, even after cancel.
+ BroadcastChannel<Integer> broadcast = BroadcastChannel.create()
+ Flow.Publisher<Integer> publisher = broadcast.asPublisher()
+
+ int n = 10
+ def subs = []
+ n.times {
+ def ref = new java.util.concurrent.atomic.AtomicReference<Flow.Subscription>()
+ publisher.subscribe(new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { ref.set(s); s.request(Long.MAX_VALUE) }
+ @Override void onNext(Integer item) {}
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() {}
+ })
+ subs << ref
+ }
+ // Subscribe registration is synchronous, so the count should be n
+ // immediately — but wait deterministically rather than guessing.
+ waitUntil { broadcast.subscriberCount == n }
+
+ subs.each { it.get().cancel() }
+ waitUntil { broadcast.subscriberCount == 0 }
+ }
+
+ @Test
+ void cancellationStopsDelivery() {
+ BroadcastChannel<Integer> broadcast = BroadcastChannel.create()
+ Flow.Publisher<Integer> publisher = broadcast.asPublisher()
+
+ List<Integer> received = []
+ def subRef = new java.util.concurrent.atomic.AtomicReference<Flow.Subscription>()
+ CountDownLatch cancelled = new CountDownLatch(1)
+
+ publisher.subscribe(new Flow.Subscriber<Integer>() {
+ @Override void onSubscribe(Flow.Subscription s) { subRef.set(s); s.request(Long.MAX_VALUE) }
+ @Override void onNext(Integer item) {
+ received << item
+ if (received.size() == 2) {
+ subRef.get().cancel()
+ cancelled.countDown()
+ }
+ }
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() {}
+ })
+
+ Thread.startDaemon {
+ try { (1..10).each { broadcast.send(it) } } catch (ChannelClosedException ignored) {}
+ }
+ // Wait until cancel has fired, plus a small grace period to confirm
+ // no further onNext signals arrive (the negative part of this test).
+ assert cancelled.await(2, TimeUnit.SECONDS)
+ Thread.sleep(50)
+ broadcast.close()
+
+ // After cancellation, the subscriber should stop receiving — exact
+ // count depends on timing but must be ≥2 and not include all 10.
+ assert received.size() >= 2
+ assert received.size() < 10
+ }
+
+ @Test
+ void forAwaitOverPublisher() {
+ // End-to-end via the FlowPublisherAdapter
+ assertScript '''
+ import groovy.concurrent.BroadcastChannel
+
+ def broadcast = BroadcastChannel.create()
+ def publisher = broadcast.asPublisher()
+
+ async {
+ Thread.sleep(30) // let consumer subscribe
+ ['x', 'y', 'z'].each { broadcast.send(it) }
+ broadcast.close()
+ }
+
+ def collected = []
+ for await (item in publisher) {
+ collected << item
+ }
+ assert collected == ['x', 'y', 'z']
+ '''
+ }
+}
diff --git a/subprojects/groovy-http-builder/src/test/groovy/groovy/http/MultiExchangeTickerEndToEndTest.groovy b/subprojects/groovy-http-builder/src/test/groovy/groovy/http/MultiExchangeTickerEndToEndTest.groovy
new file mode 100644
index 0000000000..3e787bfa81
--- /dev/null
+++ b/subprojects/groovy-http-builder/src/test/groovy/groovy/http/MultiExchangeTickerEndToEndTest.groovy
@@ -0,0 +1,261 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.http
+
+import com.sun.net.httpserver.HttpServer
+import groovy.concurrent.Agent
+import groovy.concurrent.AsyncChannel
+import groovy.concurrent.BroadcastChannel
+import groovy.concurrent.ChannelClosedException
+import groovy.json.JsonSlurper
+import org.junit.jupiter.api.AfterEach
+import org.junit.jupiter.api.BeforeEach
+import org.junit.jupiter.api.Test
+
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Flow
+import java.util.concurrent.TimeUnit
+
+import static org.apache.groovy.runtime.async.AsyncSupport.await
+
+/**
+ * End-to-end integration of {@link HttpStreamResult#bodyAsLinePublisher()},
+ * {@link BroadcastChannel#asPublisher()} and {@link Agent#changes()}.
+ * <p>
+ * Three mock exchanges stream NDJSON ticks over chunked HTTP. The pipeline
+ * fans them into a single {@link AsyncChannel}, updates a per-symbol stats
+ * {@link Agent}, and routes threshold-crossing alerts through a broadcast
+ * topic. Two independent consumers — one on the agent's change stream, one
+ * on the alert broadcast — verify the wiring end-to-end.
+ *
+ * <pre>
+ * binance (NDJSON) coinbase (NDJSON) kraken (NDJSON)
+ * │ │ │
+ * ▼ ▼ ▼
+ * getStreamAsync getStreamAsync getStreamAsync
+ * │ │ │
+ * ╰── bodyAsLinePublisher() (Flow.Publisher<String>) ──╮
+ * │
+ * for await (line in publisher) │ ← FlowPublisherAdapter
+ * │ │
+ * ▼ │
+ * AsyncChannel<Map> (unified) ◀───────╯
+ * │
+ * ▼
+ * aggregator: stats.send { … }
+ * │
+ * ▼
+ * Agent<Map<String, Map>> (per-symbol stats)
+ * │ │
+ * │ if price >= threshold
+ * ▼ ▼
+ * agent.changes() BroadcastChannel<String>
+ * Flow.Publisher │
+ * │ ╭────────────┴─────────────╮
+ * │ │ │
+ * ▼ ▼ ▼
+ * Flow.Subscriber asPublisher() subscribe()
+ * stateSnapshots Flow.Subscriber for (a in alertChannel)
+ * alertsViaPublisher alertsViaIter
+ * </pre>
+ */
+class MultiExchangeTickerEndToEndTest {
+
+ private final List<HttpServer> servers = []
+
+ @BeforeEach
+ void setup() {
+ // 3 exchanges: each emits a fixed sequence of ticks over chunked HTTP.
+ servers << buildExchange('binance', [50000, 50100, 50250, 50180])
+ servers << buildExchange('coinbase', [50050, 50120, 50300, 50220])
+ servers << buildExchange('kraken', [50010, 50090, 50260, 50190])
+ }
+
+ @AfterEach
+ void teardown() {
+ servers.each { it.stop(0) }
+ }
+
+ @Test
+ void aggregatesTicksAcrossExchangesAndPublishesAlerts() {
+ var stats = Agent.create([:].withDefault { [count: 0, last: 0d, max: 0d] })
+ var alertTopic = BroadcastChannel.create()
+ var unified = AsyncChannel.<Map>create(64)
+
+ // Subscribers register FIRST so no early signals are dropped:
+ // SubmissionPublisher drops items with no subscribers, and
+ // BroadcastChannel.subscribe() misses pre-subscription broadcasts.
+
+ var stateSnapshots = [].asSynchronized()
+ var sawSomeUpdates = new CountDownLatch(3)
+ agentChangesSubscriber(stats, stateSnapshots, sawSomeUpdates)
+
+ var alertPublisher = alertTopic.asPublisher()
+ var alertsViaPublisher = [].asSynchronized()
+ var alertsDone = new CountDownLatch(1)
+ alertPublisher.subscribe(new Flow.Subscriber<String>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(String alert) { alertsViaPublisher << alert }
+ @Override void onError(Throwable t) { alertsDone.countDown() }
+ @Override void onComplete() { alertsDone.countDown() }
+ })
+
+ // Also iterate the broadcast directly via for await (Iterable view).
+ var alertsViaIter = [].asSynchronized()
+ var alertChannel = alertTopic.subscribe()
+ Thread.startDaemon('alert-iter') {
+ for (a in alertChannel) alertsViaIter << a
+ }
+
+ // Producers and aggregator.
+
+ servers.each { server ->
+ var base = URI.create("http://127.0.0.1:${server.address.port}/")
+ var http = HttpBuilder.http(base.toString())
+ Thread.startDaemon("drain-${base}") {
+ var res = http.getStreamAsync('/ticker').join()
+ drainPublisherIntoChannel(res.bodyAsLinePublisher(), unified)
+ }
+ }
+
+ // When all 3 exchanges have published their 4 ticks each, close the
+ // unified channel so the aggregator loop exits.
+ Thread.startDaemon('unified-closer') {
+ var totalExpected = 3 * 4
+ var seen = 0
+ while (seen < totalExpected) {
+ Thread.sleep(20)
+ seen = ((Map) await(stats.getAsync())).values().sum { (int) it.count } ?: 0
+ }
+ unified.close()
+ alertTopic.close()
+ }
+
+ Thread.startDaemon('aggregator') {
+ for (Map tick in unified) {
+ // The closure passed to stats.send runs on the agent's executor
+ // and would otherwise capture the mutable for-loop variable
+ // `tick` by reference. Bind locals so the queued update sees
+ // the right values.
+ String symbol = tick.symbol
+ double price = (double) tick.price
+ stats.send { Map<String, Map> current ->
+ var symStats = current[symbol] ?: [count: 0, last: 0d, max: 0d]
+ var updated = [
+ count: ((int) symStats.count) + 1,
+ last : price,
+ max : Math.max((double) symStats.max, price),
+ ]
+ var next = new HashMap<String, Map>(current)
+ next.put(symbol, updated)
+ next
+ }
+ if (price >= 50250) {
+ try { alertTopic.send("HIGH ${symbol}@${price}".toString()) }
+ catch (ChannelClosedException ignored) {}
+ }
+ }
+ }
+
+ assert sawSomeUpdates.await(5, TimeUnit.SECONDS), 'agent.changes() did not deliver updates'
+ assert alertsDone.await(5, TimeUnit.SECONDS), 'alert publisher did not complete'
+ Thread.sleep(100) // settle
+ stats.shutdown()
+
+ Map<String, Map> finalStats = stateSnapshots[-1]
+ assert finalStats.size() == 3
+ assert finalStats['binance'].count == 4
+ assert finalStats['coinbase'].count == 4
+ assert finalStats['kraken'].count == 4
+ assert finalStats['binance'].max == 50250d
+ assert finalStats['coinbase'].max == 50300d
+ assert finalStats['kraken'].max == 50260d
+
+ // Threshold ≥ 50250: binance (50250), coinbase (50300), kraken (50260) → 3 alerts.
+ assert alertsViaPublisher.size() == 3
+ assert alertsViaIter.size() == 3
+ assert alertsViaPublisher.toSorted() == alertsViaIter.toSorted()
+ assert alertsViaPublisher.any { it.startsWith('HIGH binance@50250') }
+ assert alertsViaPublisher.any { it.startsWith('HIGH coinbase@50300') }
+ assert alertsViaPublisher.any { it.startsWith('HIGH kraken@50260') }
+ }
+
+ /** Subscribes to {@code agent.changes()} and records every snapshot. */
+ private void agentChangesSubscriber(Agent<Map<String, Map>> agent, List sink, CountDownLatch firstFew) {
+ agent.changes().subscribe(new Flow.Subscriber<Map<String, Map>>() {
+ @Override void onSubscribe(Flow.Subscription s) { s.request(Long.MAX_VALUE) }
+ @Override void onNext(Map<String, Map> snap) {
+ sink << new HashMap<>(snap)
+ firstFew.countDown()
+ }
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() {}
+ })
+ }
+
+ /** Bridges a publisher of NDJSON lines into the unified channel. */
+ private void drainPublisherIntoChannel(Flow.Publisher<String> publisher, AsyncChannel<Map> channel) {
+ var slurper = new JsonSlurper()
+ publisher.subscribe(new Flow.Subscriber<String>() {
+ Flow.Subscription sub
+ @Override void onSubscribe(Flow.Subscription s) { sub = s; s.request(Long.MAX_VALUE) }
+ @Override void onNext(String line) {
+ if (line.trim().isEmpty()) return
+ try {
+ var parsed = (Map) slurper.parseText(line)
+ // JsonSlurper returns a LazyMap whose values may share
+ // backing storage with the parser's buffer. Eagerly
+ // materialise plain types before handing off to another
+ // thread.
+ var tick = [
+ symbol: parsed.symbol.toString(),
+ price : (parsed.price as Number).doubleValue(),
+ ]
+ await channel.send(tick)
+ } catch (ChannelClosedException ignored) {
+ sub?.cancel()
+ } catch (Exception ignored) {
+ // ignore malformed line
+ }
+ }
+ @Override void onError(Throwable t) {}
+ @Override void onComplete() {}
+ })
+ }
+
+ /** Builds an HTTP server that streams NDJSON ticks for a fake exchange. */
+ private HttpServer buildExchange(String name, List<Number> prices) {
+ var server = HttpServer.create(new InetSocketAddress('127.0.0.1', 0), 0)
+ server.createContext('/ticker') { exchange ->
+ exchange.responseHeaders.add('Content-Type', 'application/x-ndjson')
+ exchange.sendResponseHeaders(200, 0) // chunked
+ exchange.responseBody.withCloseable { out ->
+ prices.each { Number p ->
+ var line = /{"symbol":"${name}","price":${p}}/ + '\n'
+ out.write(line.getBytes(StandardCharsets.UTF_8))
+ out.flush()
+ Thread.sleep(15)
+ }
+ }
+ }
+ server.start()
+ server
+ }
+}