CKTIS / Java
Java Flow contracts: subscription, demand, and termination
Learn how to establish a Flow subscription in Java SE 21, receive items with bounded demand, and distinguish normal completion, failure, and cancellation.
Version: Java SE 21
Syntax
import java.util.concurrent.Flow;
// Flow.Publisher<T>
void subscribe(Flow.Subscriber<? super T> subscriber);
// Flow.Subscriber<T>
void onSubscribe(Flow.Subscription subscription);
void onNext(T item);
void onError(Throwable error);
void onComplete();
// Flow.Subscription
void request(long n);
void cancel();In Java SE 21, the Flow types live in java.util.concurrent. Flow.Publisher<T>.subscribe accepts a Flow.Subscriber<? super T>: a subscriber that can handle T or a supertype. On successful registration, the publisher passes a new subscription to onSubscribe(Flow.Subscription) before any other callback for that subscription. Passing null to subscribe throws NullPointerException; a duplicate registration while already subscribed or a registration rejected by publisher policy is reported through onError with IllegalStateException.
The subscriber saves the handle in onSubscribe and calls request(long n) on it. A positive n adds to outstanding demand; it does not replace it. Each onNext(T item) delivers one item and uses one unit of bounded demand. Calling request(1) after processing an item lets you receive one at a time. Demand limits delivery, not the publisher's buffer capacity. Long.MAX_VALUE may be treated as effectively unbounded. On an active subscription, n <= 0 results in an onError signal carrying IllegalArgumentException, not a synchronous throw from request.
onComplete() signals normal completion; onError(Throwable) signals an unrecoverable failure. They do not consume item demand. They are mutually exclusive, and neither is followed by another callback for that subscription. Subscriber callbacks for a given subscription are ordered by happens-before, but need not run on the same thread. Do not let exceptions escape these callbacks: the contract does not guarantee recovery or a separate onError notification.
cancel() affects only that subscription. It stops delivery on a best-effort basis, not necessarily immediately: signals already in flight can still arrive. Cancellation is not normal completion; do not wait for onComplete() or onError(Throwable) after it. The example implements a subscriber and leaves subscription and delivery mechanics to the library's SubmissionPublisher.
Examples
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.TimeUnit;
public class FlowContractsDemo {
private enum Mode { COMPLETE, INVALID, CANCEL }
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
for (Mode mode : Mode.values()) {
run(executor, mode);
}
}
}
private static void run(ExecutorService executor, Mode mode) throws Exception {
System.out.println(mode);
var done = new CompletableFuture<Void>();
try (var publisher = new SubmissionPublisher<Integer>(executor, 8)) {
publisher.subscribe(new Flow.Subscriber<Integer>() {
private Flow.Subscription subscription;
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
System.out.println("onSubscribe");
subscription.request(mode == Mode.INVALID ? 0L : 1L);
}
@Override
public void onNext(Integer item) {
System.out.println("onNext " + item);
if (mode == Mode.CANCEL) {
subscription.cancel();
System.out.println("cancel");
done.complete(null);
} else if (mode == Mode.COMPLETE && item == 10) {
subscription.request(1L);
}
}
@Override
public void onError(Throwable error) {
if (mode == Mode.INVALID && error instanceof IllegalArgumentException) {
System.out.println("onError IllegalArgumentException");
done.complete(null);
} else {
done.completeExceptionally(error);
}
}
@Override
public void onComplete() {
if (mode == Mode.COMPLETE) {
System.out.println("onComplete");
done.complete(null);
} else {
done.completeExceptionally(new IllegalStateException("Unexpected completion"));
}
}
});
if (mode != Mode.INVALID) {
publisher.submit(10);
}
if (mode == Mode.COMPLETE) {
publisher.submit(20);
publisher.close();
}
done.get(10, TimeUnit.SECONDS);
}
}
}Result
COMPLETE onSubscribe onNext 10 onNext 20 onComplete INVALID onSubscribe onError IllegalArgumentException CANCEL onSubscribe onNext 10 cancel
In `COMPLETE`, the subscriber requests one item, requests one more after `10`, and receives `onComplete` after `20`. In `INVALID`, `request(0)` produces `onError` without publishing any items. In `CANCEL`, the subscriber cancels after the only published item. The program waits for the expected event instead of sleeping: `close()` does not wait for all subscriber callbacks to finish, and the cancellation case does not wait for a terminal signal.
Related lessons
- Java · Lesson 44 · Advanced · Version: 2