CKTIS / Java
Flow.Publisher — publishing items with demand control
Flow.Publisher<T> describes a source of items received by subscribers. Its subscribe method connects a receiver to the source, while Flow.Subscription lets the receiver request items and cancel delivery.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Flow.Publisher<T>
void subscribe(Flow.Subscriber<? super T> subscriber)Flow.Publisher<T> is a functional interface in java.util.concurrent. Flow.Publisher.subscribe has the signature void subscribe(Flow.Subscriber<? super T> subscriber). The ? super T wildcard accepts a receiver of T or a supertype. An accepted receiver gets onSubscribe with a Flow.Subscription; a null argument causes NullPointerException. Duplicate subscription or rejection because of policy or errors is signalled through onError with IllegalStateException.
Calling subscribe alone does not establish demand. request(n) adds demand for up to n further items; n <= 0 causes onError with IllegalArgumentException. This is backpressure, not a guarantee of exactly n deliveries. cancel() stops delivery on a best-effort basis: messages may still arrive, and no terminal signal is required.
Items arrive through onNext; onComplete indicates normal termination, while onError indicates failure. No further calls follow a terminal signal. Calls for one subscription are ordered by happens-before. Do not assume replay of earlier items or a uniform dropping policy: these depend on the implementation.
The example uses SubmissionPublisher as the implementation and calls subscribe through a Flow.Publisher<Integer> reference. The receiver requests two items. Closing the source initiates normal completion, but delivery is asynchronous, so CountDownLatch keeps the program alive until the terminal signal is handled. This demonstration wait has no timeout; operational code should plan how to handle missing completion.
Examples
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch done = new CountDownLatch(1);
try (SubmissionPublisher<Integer> source = new SubmissionPublisher<>()) {
Flow.Publisher<Integer> publisher = source;
publisher.subscribe(new Flow.Subscriber<Integer>() {
public void onSubscribe(Flow.Subscription subscription) {
subscription.request(2);
}
public void onNext(Integer item) {
System.out.println(item);
}
public void onError(Throwable error) {
System.out.println("Error: " + error.getClass().getSimpleName());
done.countDown();
}
public void onComplete() {
System.out.println("Done");
done.countDown();
}
});
source.submit(10);
source.submit(20);
}
done.await();
}
}Result
10 20 Done
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.