CKTIS / Java
Flow.Subscription — demand and cancellation
Flow.Subscription controls item delivery between a publisher and a subscriber. request(long n) increases demand, while cancel() ends reception without guaranteeing that delivery stops immediately.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
import java.util.concurrent.Flow;
Flow.Subscription subscription;
// Interface methods:
void request(long n);
void cancel();Flow.Subscription links a Flow.Publisher to a Flow.Subscriber. The subscriber receives it in onSubscribe, before other callbacks. This flow-control mechanism (backpressure) lets the receiver specify how many items it is ready to accept; without a request, it receives no items through onNext.
Flow.Subscription.request(long n) adds n to outstanding demand rather than replacing it. Fewer items may arrive if the stream terminates. Long.MAX_VALUE may mean effectively unlimited demand. On an active subscription, a call with n <= 0 signals an IllegalArgumentException to the subscriber through onError rather than throwing it synchronously from request. After the subscription is cancelled, request is a no-op, even for n <= 0.
Flow.Subscription.cancel() stops reception on a best-effort basis: further messages may still arrive. It guarantees neither onComplete nor onError. Both methods are intended only for the associated subscriber; other uses have undefined effects.
The example uses SubmissionPublisher with the Runnable::run executor to deliver tasks on the current thread without racing program termination. The subscriber requests two items and cancels after the second. The expected output is 10 and 20, each on its own line, without complete. This is a Java SE 21 example, not an attestation of a production runtime.
Examples
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
public class Main {
public static void main(String[] args) {
try (var publisher = new SubmissionPublisher<Integer>(Runnable::run, 4)) {
publisher.subscribe(new Flow.Subscriber<Integer>() {
private Flow.Subscription subscription;
private int received;
@Override
public void onSubscribe(Flow.Subscription s) {
subscription = s;
subscription.request(2);
}
@Override
public void onNext(Integer item) {
System.out.println(item);
if (++received == 2) {
subscription.cancel();
}
}
@Override
public void onError(Throwable error) {
System.out.println(error.getClass().getSimpleName());
}
@Override
public void onComplete() {
System.out.println("complete");
}
});
publisher.submit(10);
publisher.submit(20);
publisher.submit(30);
}
}
}Result
10 20
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.