Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.concurrent.Flow: practical reference

util.concurrent.Flow: practical reference: Flow groups Reactive Streams-compatible Publisher, Subscriber, Subscription, and Processor interfaces with demand control.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.concurrent.Flow

Flow groups Reactive Streams-compatible Publisher, Subscriber, Subscription, and Processor interfaces with demand control.

Use request for explicit backpressure so each subscriber states how many items it is ready to receive.

A Publisher must call onSubscribe first, signals for one subscription must be ordered, and a non-positive request terminates with onError.

No signals may follow onError or onComplete; cancel stops delivery on a best-effort basis, and implementations must handle concurrent demand safely.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

import java.util.concurrent.Flow;

public class Main {
    public static void main(String[] args) {
        Flow.Publisher<Integer> publisher = subscriber -> subscriber.onSubscribe(new Flow.Subscription() {
            private boolean done;

            public void request(long count) {
                if (done) return;
                done = true;
                if (count <= 0) {
                    subscriber.onError(new IllegalArgumentException("non-positive demand"));
                    return;
                }
                subscriber.onNext(7);
                subscriber.onComplete();
            }

            public void cancel() {
                done = true;
            }
        });

        publisher.subscribe(new Flow.Subscriber<>() {
            public void onSubscribe(Flow.Subscription subscription) { subscription.request(1); }
            public void onNext(Integer item) { System.out.println(item); }
            public void onError(Throwable error) { throw new RuntimeException(error); }
            public void onComplete() { }
        });
    }
}

Result

7

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources