Java 9 Flow: letting consumers set the pace of a measurement stream
Use Java 9 Flow and SubmissionPublisher to test demand, subscriber buffers, cancellation and slow-consumer behavior.
Archive retrospective · Topic year 2017
In this article
Separate incoming readings, active work, and pending work
A facility sends temperature and pressure readings to an operator display. A busy sensor can emit more samples per second than the screen can render. An unlimited waiting list makes the displayed picture old and drives memory use up. Dropping indiscriminately can erase an alarm that should be retained. The Flow interfaces introduced in Java SE 9 in 2017 give producers and consumers explicit demand signals. Our small measurement lab uses those interfaces and the library's SubmissionPublisher. Begin by distinguishing latest display state from events that must be retained. Demand counts items, while processing time and memory depend on each item and the work it triggers. Synthetic integers make delivery order and possible gaps straightforward to inspect.
Demand belongs to a subscription
A subscriber first receives its Subscription in onSubscribe. Requesting two allows delivery of up to two items. After processing them, requesting one adds capacity for another. These calls count items, not bytes or time. One object may still be large and expensive. Outstanding demand adds up as new requests arrive and is consumed by subsequent delivery. A subscriber that wants to leave calls cancel; work already racing with cancellation may have started. Define who owns those results and whether they should still reach a durable store. A zero or negative request is invalid. With two subscribers on one publisher, one can ask for two and the other for many. Their demands belong to their individual subscriptions.
Exercise two items followed by one
The Java 9 example subscribes once and submits 11, 12, and 13. The subscriber requests two, then asks for one more after receiving the second. At completion it copies the observed values into a future, so the caller can verify the expected order. A timeout catches a hung test and is not a service latency objective. Keep callbacks short: a single executor thread handling slow work may delay delivery. For a separate demand test, remove the third request and observe only the first two values before cancellation. Do not wait for ordinary completion in a test that deliberately leaves a buffered item without demand. Verify terminal behavior independently from the item-count expectation.
// Run inside a Java 9 test method. Imports: java.util.*, java.util.concurrent.*.
List<Integer> seen = new ArrayList<>();
CompletableFuture<List<Integer>> result = new CompletableFuture<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
try (SubmissionPublisher<Integer> pub = new SubmissionPublisher<>(executor, 8)) {
pub.subscribe(new Flow.Subscriber<Integer>() {
private Flow.Subscription sub;
public void onSubscribe(Flow.Subscription s) { sub = s; sub.request(2); }
public void onNext(Integer value) {
seen.add(value);
if (seen.size() == 2) sub.request(1);
}
public void onError(Throwable error) { result.completeExceptionally(error); }
public void onComplete() { result.complete(new ArrayList<>(seen)); }
});
for (Integer value : Arrays.asList(11, 12, 13)) pub.submit(value);
}
if (!result.get(2, TimeUnit.SECONDS).equals(Arrays.asList(11, 12, 13))) {
throw new AssertionError("Unexpected delivery or order");
}
} finally {
executor.shutdownNow();
}
Choose what a full buffer means for the product
SubmissionPublisher has finite subscriber buffers. When they fill, submit may block until space becomes available. The producing system must decide whether it can tolerate that wait. An offer call and a drop handler can support a different policy. A dashboard may explicitly tolerate missed intermediate snapshots. A billing reading or an alarm cannot quietly disappear under the same policy. Persist those events first and use the live stream as a notification path. A display that notices a missed sequence can reload a consistent snapshot from the authoritative store. Test memory with realistic message sizes. Eight small integer readings and eight binary objects impose very different costs. Count actual drops rather than interpreting an estimated lag as proof that all items arrived.
Exercise a slow consumer and resynchronization
Pause demand on one subscription and replenish it on another after each delivery. Sleeping a callback on a shared worker can stop both subscribers and tests a different mechanism. Submit a burst with offer and record deliveries, drops, and the last sequence received by each subscriber. Reconnect the slow subscriber and show that it sees new submissions. A new subscription does not replay a historical stream automatically. When the display detects a gap, fetch the current authoritative state and compare sequence numbers before applying live events. An older buffered item must not overwrite a newer snapshot. Keeping the last applied sequence in the update condition makes the recovery behavior testable. A burst from a real producer can then be compared with the synthetic test.
Observe the outcomes you depend on
Record produced readings, deliveries, drops, and cancellations separately. On shutdown, verify completion of durable work before terminating an alarm service. In the display, mark when an observer stopped and record any callback still in flight when its executor is closed. Track the age of the latest visible value as well as the total number delivered. Throughput alone cannot establish that the operator saw the current state. Java 9 Flow makes consumer demand part of the protocol. The application still chooses durability, acceptable loss, and what users see after reconnecting. A useful acceptance test demonstrates that different message categories continue to obey their different rules when one receiver slows down.
Reader discussion
How would you measure this development's real-world impact?
No comments yet. Be the first to contribute.
Write a comment